What does setInterval() do?
What setInterval() does
setInterval() is a built-in JavaScript function that:
- starts a periodic timer,
- every
delaymilliseconds adds the given callback to the macrotask queue, - 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 stoppedEvery 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
setInterval()registers the timer with an external API (Web API / Node Timer API).- Every
delayms the Web API adds the callback to the macrotask queue (Task Queue). - The Event Loop runs the callback when the call stack is empty.
- 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 run2. 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 5Difference between setInterval() and setTimeout()
| Property | setTimeout() | setInterval() |
|---|---|---|
| Runs | Once | Repeatedly |
| Repetition | No | Yes |
| Returns | Timer ID | Interval ID |
| Cancellation | clearTimeout(id) | clearInterval(id) |
| Queue | Macrotasks | Macrotasks |
| Used for | Deferred execution | Repeating tasks |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.