Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

The setInterval() Method

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.

Example

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.

How to Stop the Execution?

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);

Example

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>