Skip to main content

What does setInterval() do?

What setInterval() does

setInterval() is a built-in JavaScript function that:

  1. starts a periodic timer,
  2. every delay milliseconds adds the given callback to the macrotask queue,
  3. keeps doing this until clearInterval() is called.

Syntax

javascript
setInterval(callback, delay, ...args);

Parameters:

  • callback - the function to call repeatedly;
  • delay - the interval between runs, in milliseconds;
  • ...args - extra arguments passed to the callback.

Example

javascript
let count = 0; const id = setInterval(() => { count++; console.log(`${count} seconds have passed`); if (count === 5) { clearInterval(id); console.log('Timer stopped'); } }, 1000);

What happens:

javascript
1 seconds have passed 2 seconds have passed 3 seconds have passed 4 seconds have passed 5 seconds have passed Timer stopped

Every second a new function is added to the task queue, and it runs when the stack is empty.


What setInterval() returns

It returns a numeric interval identifier (ID) - the same type as setTimeout() returns.

This ID is used to stop the timer:

javascript
const intervalId = setInterval(() => console.log('tick'), 1000); // stop it after 5 seconds setTimeout(() => clearInterval(intervalId), 5000);

How it works under the hood

  1. setInterval() registers the timer with an external API (Web API / Node Timer API).
  2. Every delay ms the Web API adds the callback to the macrotask queue (Task Queue).
  3. The Event Loop runs the callback when the call stack is empty.
  4. The cycle repeats until clearInterval() is called.

Important to know

1. Interval does not mean exact timing

setInterval does not guarantee the callback fires exactly after delay ms. If the engine is busy (for example, running heavy code), the run is delayed.

javascript
setInterval(() => console.log('tick'), 1000); while (true) {} // the page "hangs", intervals never run

2. Calls can pile up

If the callback takes longer than the interval itself, tasks will pile up in the queue:

javascript
setInterval(() => { const start = Date.now(); while (Date.now() - start < 2000) {} // blocks the thread for 2 sec console.log('Call'); }, 1000);

The interval is 1 s, but execution takes 2 s - callbacks will "crowd" the queue and run one after another, with no pauses.


3. You can pass arguments

javascript
setInterval((a, b) => console.log(a + b), 1000, 2, 3); // -> Every second it prints 5

Difference between setInterval() and setTimeout()

PropertysetTimeout()setInterval()
RunsOnceRepeatedly
RepetitionNoYes
ReturnsTimer IDInterval ID
CancellationclearTimeout(id)clearInterval(id)
QueueMacrotasksMacrotasks
Used forDeferred executionRepeating tasks

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.