The setInterval()
method, offered on the Window
and WorkerGlobalScope
interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
Syntax
intervalID = setInterval ( function , delay , arg0 , arg1 , /* … , */ argN )
- The
function
to be executed or, alternatively, a code snippet. - The
delay
in milliseconds between each execution. This parameter is optional and if not provided defaults to 0. - Optional additional arguments (
arg0
,arg1
…argN
), which are passed to thefunction
once the timer expires.
It returns a numeric, non-zero value as intervalID
of the timer created by the call to setInterval()
. This intervalID
value can be passed to clearInterval()
to cancel the interval.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 | let i = 1; // Initial count const iMax = 3; // Max count // Function passed to `setInterval()` method function sayHello() { console.log('Hello number ' + i); i = i + 1; if (i > iMax) { clearInterval(intervalID); // Canceling the repeating action of the `setInterval()` method } } const intervalID = setInterval(sayHello, 1000); // Calling the `setInterval()` method |
Output:
1 2 3 | Hello number 1 Hello number 2 Hello number 3 |
Examples
Example 1: Basic syntax
1 2 3 4 5 6 7 8 | const intervalID = setInterval(myCallback, 500, "Parameter 1", "Parameter 2"); function myCallback(a, b) { // Your code here // Parameters are purely optional. console.log(a); console.log(b); } |
Example 2: Alternating two colors
HTML
1 2 3 4 5 | <div id="my_box"> <h3>Hello World</h3> </div> <button id="start">Start</button> <button id="stop">Stop</button> |
CSS
1 2 3 4 5 6 | .go { color: green; } .stop { color: red; } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // variable to store our intervalID let nIntervId; function changeColor() { // check if an interval has already been set up if (!nIntervId) { nIntervId = setInterval(flashText, 1000); } } function flashText() { const oElem = document.getElementById("my_box"); oElem.className = oElem.className === "go" ? "stop" : "go"; } function stopTextColor() { clearInterval(nIntervId); // release our intervalID from the variable nIntervId = null; } document.getElementById("start").addEventListener("click", changeColor); document.getElementById("stop").addEventListener("click", stopTextColor); |
Comments 1