CodePark/ questions / Event loop phases
START PRACTICINGPRACTICE
Backend question · Node.js › Event loop phases

Compare process.nextTick, setImmediate and setTimeout(fn, 0). When would you use each?

All three run a function later, but at different moments:

  • process.nextTick(fn) runs fn as soon as the current operation finishes. It runs before promise microtasks and before the event loop moves on.
  • setImmediate(fn) runs in the check phase. This phase comes right after the poll phase (where Node waits for and handles I/O) in the current loop iteration.
  • setTimeout(fn, 0) runs in the timers phase, once at least 1 ms has passed. Node treats 0 as 1.

The names are confusing: nextTick is the more immediate one.

When to use each:

  • Use nextTick rarely. One good case: emit an event or call a callback asynchronously, so the caller first has time to attach listeners. Node empties the whole nextTick queue before it continues. So if a nextTick callback keeps scheduling more nextTick calls, I/O never gets a turn. This is called starving I/O.
  • Use setImmediate to let I/O run first, for example when you break a long job into chunks.
  • Use setTimeout when you really need a delay.
  • nextTick runs before promises and before the event loop continues.
  • setImmediate runs in the check phase, after the poll phase.
  • setTimeout(0) runs in the timers phase, after at least 1 ms.
  • Recursive nextTick calls starve I/O. Recursive setImmediate calls do not.
  • Prefer setImmediate when you want to give I/O a turn.