Back to results for “Set”
Node.js › Advanced Node.js

What is the difference between process.nextTick(), setImmediate(), and setTimeout(fn, 0) in terms of execution order?

Advanced

Answer

process.nextTick() queues a callback to run immediately after the current operation completes, before the event loop continues to any phase -- it has the highest priority and can starve I/O if called recursively. setImmediate() queues a callback to run in the check phase of the event loop, after I/O callbacks in the current iteration. setTimeout(fn, 0) queues a callback for the timers phase, and its exact ordering relative to setImmediate() from the main module is not guaranteed, though inside an I/O callback setImmediate() always fires first.
console.log('start');
setTimeout(() => console.log('setTimeout'), 0);
setImmediate(() => console.log('setImmediate'));
process.nextTick(() => console.log('nextTick'));
console.log('end');
// Output: start, end, nextTick, then setTimeout/setImmediate (order can vary at top level)
Real-world example A library author uses process.nextTick() to guarantee that a callback passed synchronously to a constructor is still always invoked asynchronously (never synchronously), preserving a predictable execution contract for consumers regardless of whether the underlying operation happens to resolve instantly.

Common follow-ups: Why can excessive use of process.nextTick() starve the event loop of I/O callbacks?;In what specific case is setImmediate() ordering guaranteed relative to setTimeout()?