Node.js theorytheory 0/50 · 0%
Foundations · easy

14. Timers

setTimeout, setInterval, setImmediate and their ordering.

`setTimeout(fn, ms)` schedules a one-off callback after at least `ms` milliseconds; `setInterval(fn, ms)` repeats it; both return a handle that `clearTimeout`/`clearInterval` can cancel. `setImmediate(fn)` (Node-specific) runs after the current I/O phase completes, generally before timers scheduled for the same tick.

js
const id = setInterval(() => console.log("tick"), 1000);
setTimeout(() => clearInterval(id), 5000); // stop after 5 ticks

setImmediate(() => console.log("after I/O"));

Timers are not exact: `ms` is a minimum delay, not a guarantee, because the event loop must also process other queued work first. Never rely on a timer for precise real-time behaviour.

Check your understanding

  1. 1. What does the ms argument to setTimeout guarantee?

  2. 2. How do you stop a repeating setInterval?

  3. 3. What is setImmediate used for?