Node.js Reference ยท Concepts and Pitfalls
Node.js event loop phases
The phases of the Node.js event loop explained with runnable examples: timers, pending, poll, check and close callbacks, plus nextTick and promise microtasks.
The event loop is what lets one JavaScript thread serve thousands of connections. It runs your code to completion, then looks for more work: expired timers, finished I/O, scheduled callbacks. libuv, the C library under Node, organizes that work into phases. Each trip around the loop is called a tick, and each phase has its own queue of callbacks.
Knowing the phases explains puzzling orderings: why setImmediate sometimes beats setTimeout(fn, 0), why process.nextTick runs before promise callbacks, and why a long synchronous function delays everything. Between every callback, Node also drains two microtask queues, which are not phases themselves.
flowchart LR
T["timers<br/>setTimeout, setInterval"] --> P["pending callbacks<br/>deferred system errors"]
P --> I["idle, prepare<br/>internal"]
I --> L["poll<br/>I/O callbacks, waits for events"]
L --> C["check<br/>setImmediate"]
C --> X["close callbacks<br/>socket.on('close')"]
X --> TPhases in the order libuv visits them. After each callback, process.nextTick and promise callbacks run.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
The phases
- Timers. Runs callbacks of
setTimeout()andsetInterval()whose time has come. The delay is a minimum, not a promise: a timer fires on the first loop pass after its time, so a busy loop makes it late. - Pending callbacks. Runs a few deferred system-level callbacks, such as some TCP error reports. You rarely think about it.
- Idle, prepare. Internal use only.
- Poll. The heart of the loop. It executes I/O callbacks (finished file reads, incoming socket data) and, if nothing else is scheduled, blocks and waits for new events, but only for as long as the nearest timer allows. If
setImmediatecallbacks are queued, poll does not wait and moves on to check. - Check. Runs
setImmediate()callbacks, right after poll. That is whysetImmediateis the way to say "after the current I/O". - Close callbacks. Runs
'close'handlers of sockets and handles that were destroyed abruptly.
Microtasks and nextTick
After the current operation finishes, and again after each callback in a phase, Node empties these queues:
- the
process.nextTickqueue, then - the promise (microtask) queue, repeating both until nothing is left.
So process.nextTick runs before promise callbacks scheduled at the same time, and both run before the loop moves on to the next callback. A callback that keeps scheduling new microtasks can starve the loop; I/O and timers never get their turn.
In an ES module, the main file itself runs inside a promise job, so promise callbacks queued at the top level run before nextTick callbacks. In a CommonJS file, nextTick goes first. Inside later callbacks, as the first example shows, nextTick goes first in both.
Usage notes
setTimeout(fn, 0)is really 1 ms (delays below 1 are raised to 1), and its ordering againstsetImmediatefrom the main module depends on how busy the process was when the loop started. Inside an I/O callback,setImmediatealways runs first.- Use
setImmediateto yield to I/O between chunks of work. Prefer it toprocess.nextTickfor that purpose, becausenextTickcallbacks run before the loop advances and cannot let I/O through. - Use
queueMicrotask()or promises for "as soon as the current code is done",process.nextTickonly when you need it to run before promises. - Unref'd handles (
timer.unref()) do not keep the loop alive; the process exits when no ref'd work remains. - The loop exits when no timers, I/O handles or pending requests remain. A listening server keeps it alive; a completed
fetchdoes not. - Worker threads each have their own event loop and phases.
- Long synchronous code blocks every phase. See Blocking the event loop.