Window setInterval()
Examples
Display "Hello" every second (1000 milliseconds):
Call displayHello every second:
More examples below.
Description
The setInterval()
method calls a function at specified intervals (in milliseconds).
The setInterval()
method continues calling the function until
clearInterval()
is called, or the window is closed.
1 second = 1000 milliseconds.
Note
To execute the function only once, use the setTimeout()
method instead.
To clear an interval, use the id returned from setInterval():
Then you can to stop the execution by calling clearInterval():
See Also:
Syntax
Parameters
The function to execute
The execution interval.
If the value is less than 10, 10 is used
Additional parameters to pass to the function
Not supported in IE9 and earlier.
Return Value
Use this id with clearInterval() to cancel the timer.
More Examples
Example
Display the time like a digital watch:
function myTimer() {
const date = new Date();
document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
Example
Using clearInterval() to stop the digital watch:
function myTimer() {
const date = new Date();
document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
function myStopFunction() {
clearInterval(myInterval);
}
Example
Using setInterval() and clearInterval() to create a dynamic progress bar:
const element = document.getElementById("myBar");
let width = 0;
let id = setInterval(frame, 10);
function frame() {
if (width == 100) {
clearInterval(id);
} else {
width++;
element.style.width = width + '%';
}
}
}
Example
Toggle between two background colors once every 500 milliseconds:
function setColor() {
let x = document.body;
x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}
function stopColor() {
clearInterval(myInterval);
}
Example
Pass parameters to the function (does not work in IE9 and earlier):
However, if you use an anonymous function it works in all browsers:
Browser Support
setInterval()
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |