What is the difference between setTimeout and setImmediate in Node.js?
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.