Node.js Developer interview question · Most asked

What is the difference between `process.nextTick`, Promise microtasks, `setImmediate` and `setTimeout(fn, 0)`?

Summary

process.nextTick callbacks run immediately after the current operation, before Promise microtasks; Promise callbacks (then, await continuations) run next; setImmediate runs in the check phase of the loop; setTimeout(fn, 0) runs in the timers phase (at least about 1 ms later).

Longer Answer

Recursive nextTick (or endless microtasks) can starve I/O because the queues are drained completely before the loop continues. Prefer queueMicrotask or setImmediate for deferring work. The order between setTimeout(0) and setImmediate in the main module is non-deterministic.

Key Points

  • nextTick > microtasks > macrotasks
  • setImmediate: check phase
  • setTimeout(0): timers phase
  • Recursive nextTick can starve I/O

More most-asked Node.js Developer questions

← All Node.js Developer questions