offline version v3


141 of 264 menu

setInterval function

The setInterval function executes the code at the specified time interval. Callback should be passed as the first parameter, and the time in milliseconds indicating the interval after which the code set by the first one will be repeated as the second parameter. The function returns a unique identifier that can be used to stop the timer. To do this, this identifier should be passed to the clearInterval function.

Syntax

setInterval(function, time);

Example

Let's start a timer that prints some text to the console every second:

setInterval(function() { console.log('text'); }, 1000);

Example

Let's start a timer that prints integers to the console every second in ascending order:

let i = 0; setInterval(function() { console.log(i++); }, 1000);

Example

Stop the timer when the counter reaches the value 10:

let i = 0; let id = setInterval(function() { i++; if (i == 10) { clearInterval(id); } else { console.log(i); } }, 1000);

See also

  • the setTimeout function
    that sets a delay before executing the code
enru