Mid-level (2-5 years)Node.js

What is the difference between process.nextTick, setImmediate and setTimeout in Node.js?

Quick answer

process.nextTick runs its callback right after the current operation, before the event loop continues; setTimeout runs in the timers phase after a minimum delay; and setImmediate runs in the check phase right after the poll (I/O) phase.

The Node.js event loop has phases: timers, pending callbacks, poll (I/O), check (setImmediate) and close callbacks. The nextTick queue and the promise microtask queue are drained between phases, and the nextTick queue goes first. Recursively calling process.nextTick can therefore starve I/O.

From the main module, the order of setTimeout(fn, 0) and setImmediate(fn) depends on process timing and is not guaranteed. Inside an I/O callback, setImmediate always runs first. Prefer setImmediate or queueMicrotask for deferring work, and reserve nextTick for cases such as emitting an event after a constructor returns.

setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
// nextTick, promise, then timeout/immediate (order of last two varies)