Spring Fresh Sale! - Up To 67% OFF BDIX Hosting + Free Domain
Node.js

process.nextTick vs setImmediate vs setTimeout: Execution Order in Node.js

process.nextTick, setImmediate and setTimeout all defer work, but they run at different points in the event loop — and mixing them up leads to subtle timing bugs. Here is what each does and the order they actually fire.

The three, in plain terms

  • process.nextTick(fn) — runs before the event loop continues, right after the current operation. The soonest of the three.
  • Promise callbacks — run just after the nextTick queue, in the microtask queue.
  • setImmediate(fn) — runs in the check phase, after the current poll phase completes.
  • setTimeout(fn, 0) — runs in the timers phase on a later loop iteration.

The ordering that trips people up

From the main module, setTimeout(fn, 0) and setImmediate can fire in either order — it depends on process timing. But inside an I/O callback, setImmediate always runs before a setTimeout(fn, 0), because the loop hits the check phase before looping back to timers. This determinism is why setImmediate is preferred for "run after this I/O completes".

Why nextTick needs care

Because process.nextTick runs before the loop proceeds, scheduling nextTick callbacks recursively can starve the event loop — I/O never gets a chance to run. Use it sparingly, for genuinely urgent deferral. For understanding the phases involved, see the event loop guide.

When to use which

  • setImmediate — to run something after the current I/O phase; the safe default for "soon, but yield first".
  • setTimeout — to genuinely delay by a time.
  • process.nextTick — rarely; for firing an event before any I/O, or ensuring a callback runs asynchronously in an API.

Frequently asked questions

Which runs first, nextTick or a Promise?

The process.nextTick queue is drained before the Promise microtask queue, so nextTick callbacks run first. Both run before the loop moves to the next phase.

Is setImmediate the same as setTimeout(fn, 0)?

No. They live in different phases. Inside I/O callbacks their order is deterministic (setImmediate first); from the main module it can vary. Use setImmediate when you specifically want post-poll execution.

Can nextTick crash my app?

Recursive nextTick can starve the loop so I/O never runs, effectively hanging the app. Keep nextTick usage shallow and prefer setImmediate for repeated deferral.

Was this article helpful?