The setInterval()
method repeatedly executes a specified function at the defined time interval.
window.setInterval(function, milliseconds); |
The setInterval()
method can be used without the window
prefix.
The first parameter is the function to execute, and the second parameter specifies the time interval between each execution.
This example runs a function called “myTimer” every second, similar to a digital watch.
Show the current time.
setInterval(myTimer, 1000); function myTimer() { const d = new Date(); document.getElementById(“demo”).innerHTML = d.toLocaleTimeString(); } |
One second is equal to 1000 milliseconds. |
The clearInterval()
method stops the repeated execution of the function set by setInterval()
.
window.clearInterval(timerVariable) |
The clearInterval()
method can be used without the window
prefix.
It takes the variable returned by setInterval()
as its argument.
let myVar = setInterval(function, milliseconds); clearInterval(myVar); |
The same example as above, but with an added “Stop time” button.
<p id=”demo”></p> <button onclick=”clearInterval(myVar)”>Stop time</button> <script> let myVar = setInterval(myTimer, 1000); function myTimer() { const d = new Date(); document.getElementById(“demo”).innerHTML = d.toLocaleTimeString(); } </script> |