Skip to the page

The event loop · senior

The Node.js event loop: nextTick, setImmediate and timers

Node's event loop (libuv) runs in phases — timers, pending callbacks, poll (I/O), check (setImmediate), close — and between callbacks it first drains the process.nextTick queue, then the promise microtask queue.

The notes

What you must know

  • Phases: timers -> pending callbacks -> idle/prepare -> poll (wait for I/O) -> check (setImmediate) -> close callbacks.
  • The process.nextTick queue runs before promise microtasks, and both drain after each callback.
  • setTimeout(0) vs setImmediate in the main module: the order is not deterministic. Inside an I/O callback, setImmediate always runs first.
  • Recursive process.nextTick can starve I/O, just like endless microtasks.
  • Use setImmediate to yield to I/O; promises or queueMicrotask for 'right after this'; nextTick mostly inside libraries (for example to emit an event after the constructor returns).
  • CPU-heavy work blocks every request on the server; move it to worker_threads.

The red pen

Common traps: mistake → fix

  • Mistake: Node and browser event loops are the same

    Fix: Node has phases, nextTick and setImmediate, and no rendering.

  • Mistake: setImmediate runs immediately

    Fix: it runs in the check phase, after poll.

Easy to hard

Questions interviewers ask, easy to hard

  1. Order these: process.nextTick, Promise.then, setTimeout 0, setImmediate.
  2. Why is setTimeout 0 vs setImmediate non-deterministic in the main module but fixed inside an I/O callback?
  3. What can starve the Node event loop?
  4. How do you keep a Node server responsive when some requests do heavy CPU work?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview