Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

setInterval — calling a function repeatedly

setInterval() schedules repeated function calls with a requested delay in milliseconds. Its returned identifier lets you stop the timer with clearInterval(); exact execution timing is not guaranteed.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const intervalId = setInterval(callback, delayMs, ...args);
clearInterval(intervalId);

setInterval(callback, delayMs, ...args) is a Web API defined by the HTML standard, not ECMAScript. It is available in browser windows and workers and supported by current browser engines. The presence of this name in Node.js does not prove browser API support.

Pass a function as callback, a delay in milliseconds as delayMs, and optional arguments as ...args. The first call is not immediate. The method returns a positive integer timer identifier; retain it and pass it to clearInterval(intervalId) when the timer is no longer needed. Unlike the one-shot setTimeout(), this timer repeats calls.

The delay does not guarantee an exact schedule: other tasks can postpone execution. When the timer nesting level exceeds 5, delays below 4 ms are raised to 4 ms; this also applies to setInterval() repetitions. Pass a function rather than a string containing code.

The example prints 1, 2, 3 in order and cancels the timer during its third call. Verify the order and termination, not exact time intervals.

Examples

{
  let count = 0;
  const intervalId = setInterval(() => {
    count += 1;
    console.log(count);
    if (count === 3) {
      clearInterval(intervalId);
    }
  }, 100);
}

Result

1
2
3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources