Node schedules work with setTimeout, setInterval, and setImmediate. Timers are macrotasks—they run after current sync code and microtasks complete.
Common APIs
setTimeout(fn, ms)— run once after delay (minimum delay not guaranteed under load)setInterval(fn, ms)— repeat untilclearIntervalsetImmediate(fn)— run after I/O callbacks in the check phase
Promisified sleep
await new Promise(r => setTimeout(r, 1000));
Use sparingly in tests or retries—not for throttling production traffic (use proper rate limiters).
Important interview questions and answers
- Q: setImmediate vs setTimeout(0)?
A: Order differs by context; both schedule macrotasks—prefer one style consistently in codebases. - Q: clearTimeout?
A: Cancels a scheduled timer—store the returned id when debouncing user input.
Self-check
- Are timers microtasks or macrotasks?
- Why not use busy-wait loops for delays?