What is the difference between setTimeout and setImmediate in Node.js?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Node.js development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
setTimeout(fn, 0) schedules a callback to run after the current event loop cycle, in the timers phase of the next iteration, after a minimum delay (at least ~1ms even if 0 is specified). setImmediate(fn) schedules a callback to run in the check phase of the current event loop iteration — after I/O events and before timers in the next iteration. In practice: when both are called from the main module, their execution order is non-deterministic (depends on process performance). But when called within an I/O callback, setImmediate() always executes before setTimeout(fn, 0). process.nextTick(fn) is different from both — it fires immediately after the current operation completes, before the event loop continues to its next phase. Use process.nextTick() to ensure a callback fires before any I/O; use setImmediate() to yield to the event loop and then run.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Node.js answers easy to follow.