Full answer
Both functions hand a callback to the timer system, return an identifier (a number in browsers, an object in Node.js), and let the event loop run the callback later. clearTimeout(id) and clearInterval(id) cancel it. Extra arguments after the delay are passed to the callback.
The delay is the earliest time the callback can run. It is placed in the macrotask queue when the time is up, but it still waits for the current code and any queued microtasks. A zero delay does not mean immediately, and browsers may raise very short delays for nested timers. Timers in background tabs can be slowed down further.
The classic mistake is writing setTimeout(doWork(), 1000). The parentheses call doWork right away, and the timer receives its return value. Browsers accept that silently and schedule nothing useful, while Node.js throws an error because the callback is not a function. Pass the function itself, setTimeout(doWork, 1000), or wrap it in an arrow function when arguments are needed.
setInterval has its own problems. It does not wait for the callback to finish, so a slow callback can run again right after the last one, and intervals drift when the main thread is busy. An interval that is never cleared keeps running and holds everything its callback references. A safer pattern is a function that schedules the next setTimeout after finishing its work, which guarantees a gap between runs.
Regular function callbacks lose this when passed to a timer. Use an arrow function or bind.
For animation, requestAnimationFrame is better than a short interval, since it matches the screen refresh.
const log = [];
setTimeout(() => log.push('timer 10 ms'), 10);
setTimeout(() => log.push('timer 0 ms'), 0);
log.push('sync');
function sayHello() {
log.push('hello called right away');
return undefined;
}
try {
setTimeout(sayHello(), 1000); // bug: sayHello runs now and undefined is passed as the callback
} catch (error) {
log.push('Node.js rejects the bad callback: ' + error.code);
}
setTimeout((name, mark) => log.push(`args: ${name} ${mark}`), 5, 'Asha', 90);
const cancelled = setTimeout(() => log.push('never runs'), 5);
clearTimeout(cancelled);
const counter = {
count: 0,
startBroken() {
setTimeout(function () {
log.push('regular function this.count: ' + this?.count);
}, 1);
},
startFixed() {
setTimeout(() => log.push('arrow function this.count: ' + this.count), 1);
},
};
counter.startBroken();
counter.startFixed();
let ticks = 0;
const id = setInterval(() => {
ticks += 1;
log.push(`interval tick ${ticks}`);
if (ticks === 3) clearInterval(id);
}, 15);
let step = 0;
function selfScheduling() {
step += 1;
log.push(`self-scheduled step ${step}`);
if (step < 2) setTimeout(selfScheduling, 20);
}
setTimeout(selfScheduling, 100);
setTimeout(() => console.log(log.join('\n')), 300);Run with Node.js v24.22.1 as js-61.js; two runs gave identical output. Output: sync hello called right away Node.js rejects the bad callback: ERR_INVALID_ARG_TYPE timer 0 ms regular function this.count: undefined arrow function this.count: 0 args: Asha 90 timer 10 ms interval tick 1 interval tick 2 interval tick 3 self-scheduled step 1 self-scheduled step 2
Key points
- The delay is a minimum; the callback waits for the stack and microtasks.
- Pass the function, not its call: setTimeout(fn, ms), not setTimeout(fn(), ms).
- Always keep the id and clear intervals and timeouts when they are no longer needed.
- setInterval can overlap or drift; a self-scheduling setTimeout keeps a gap.
- Use requestAnimationFrame for animation.
Common mistakes
- Passing the result of a call, setTimeout(fn(), ms), instead of the function.
- Never clearing an interval that is created in a component or page that goes away.
- Relying on exact timing; the delay is a minimum.
- Using a regular function callback that expects this to be the surrounding object.
Follow-ups
- Why can a setInterval callback run twice in quick succession?
- What are the differences between setTimeout, setImmediate, and requestAnimationFrame?
- How would you write a timer that does not drift over a long period?
Tips
- Say "minimum delay" and explain the macrotask queue in one sentence.
- Show the self-scheduling setTimeout pattern as the safer alternative to setInterval.
- Mention clearing timers on teardown; it links to memory leaks.