Window clearInterval() method
Example
Display the current time (the setInterval() function executes a function once per second, like a watch). Use clearInterval() to stop execution:
var
myVar
=
setInterval
(
function
(
)
{
myTimer
(
)
}
,
1000
)
;
function
myTimer
(
)
{
var
d
=
new
Date
(
)
;
var
t
=
d
.
toLocaleTimeString
(
)
;
document
.
getElementById
(
"
demo
"
)
.
innerHTML
=
t
;
}
function
myStopFunction
(
)
{
clearInterval
(
myVar
)
;
}
Try it »
Definition and Usage
The clearInterval() method cancels a timed operation set by the setInterval() function.
The parameter of the clearInterval() method must be the ID value returned by setInterval().
Note: To use the clearInterval() method, you must use a global variable when creating the timed operation:
myVar = setInterval("javascript 函数", milliseconds);
You can stop the execution using the clearInterval() method.
Browser support
The numbers in the table indicate the first browser version that supports this property.
| Method | |||||
|---|---|---|---|---|---|
| clearInterval() | 1.0 | 4.0 | 1.0 | 1.0 | 4.0 |
Syntax
clearInterval(id_of_setinterval)
| Parameters | Description |
|---|---|
| id_of_setinterval | The return value obtained when calling the setInterval() function can be used as a parameter to cancel the timed operation set by that setInterval(). |
Technical Details
| Return value: | No value is returned. |
|---|
More examples
Example
Switch the background color every 300 milliseconds until stopped via clearInterval():
var
myVar
=
setInterval
(
function
(
)
{
setColor
(
)
}
,
300
)
;
function
setColor
(
)
{
var
x
=
document
.
body
;
x
.
style
.
backgroundColor
=
x
.
style
.
backgroundColor
==
"
yellow
"
?
"
pink
"
:
"
yellow
"
;
}
function
stopColor
(
)
{
clearInterval
(
myVar
)
;
}
Try it »
Example
Use setInterval() and clearInterval() to create a dynamic progress bar:
function
move
(
)
{
var
elem
=
document
.
getElementById
(
"
myBar
"
)
;
var
width
=
0
;
var
id
=
setInterval
(
frame
,
100
)
;
function
frame
(
)
{
if
(
width
==
100
)
{
clearInterval
(
id
)
;
}
else
{
width
++;
elem
.
style
.
width
=
width
'
%
'
;
}
}
}
Try it »
Related pages
Window object: setInterval() method
Window object: setTimeout() method
Window object: clearTimeout() method
Window Object