Skip to content

Lesson 2 of 9 · 26m

Event-Loop Phases, Timers, and I/O Callback Ordering

Learn what each event-loop phase actually runs, why timer ordering is conditional, and how to reason about callbacks without cargo-cult diagrams.

Most event-loop diagrams are just accurate enough to get you into trouble. They draw neat boxes — timers, poll, check — and then production asks why setTimeout(fn, 0) sometimes runs before an I/O callback and sometimes after it. The answer is not mystical. The event loop is a sequence of phases, and the exact point where a wake-up is observed depends on when the loop got there.

The phases you actually need

libuv's loop can be usefully reduced to this sequence:

timers       -> expired setTimeout/setInterval callbacks
pending      -> deferred system-level callbacks
poll         -> wait for and dispatch I/O events
check        -> setImmediate callbacks
close        -> close-handle callbacks such as socket 'close'

Microtasks are interleaved around callbacks but are not a separate libuv phase. That distinction matters. Promises are JavaScript machinery; sockets and timers are libuv machinery.

Timers are thresholds, not alarms

setTimeout(fn, 20) means "run no earlier than roughly 20 milliseconds," not "run at exactly 20 milliseconds." If the loop is busy parsing a 30 MB JSON payload, the timer waits:

const started = Date.now();
setTimeout(() => console.log('timer delay:', Date.now() - started), 20);

const until = started + 80;
while (Date.now() < until) {
  // synchronous work starves the loop
}

That script prints a delay closer to 80 milliseconds. Nothing is broken. The loop could not return to the timers phase while JavaScript occupied the main thread.

setImmediate is phase-relative

setImmediate schedules work in the check phase, after the poll phase of the current iteration. Inside an I/O callback it is usually predictable. At top level, timer-versus-immediate ordering is intentionally less certain because the loop may enter timers or poll first depending on setup time.

fs.readFile('/etc/hosts', () => {
  setImmediate(() => console.log('immediate'));
  setTimeout(() => console.log('timeout'), 0);
});

In the I/O callback, the immediate normally wins because the loop is already in the I/O path and check comes before the next timer pass.

Use ordering deliberately

setImmediate is for yielding after the current I/O cycle. setTimeout(..., 0) is a coarse timer. process.nextTick and promise continuations are different again. Do not use scheduling primitives as decorative async seasoning; use them to express exactly when work should happen.

Production implications

Long timer delays are often symptoms, not causes. If health checks time out while CPU is low, suspect the loop cannot reach the poll phase promptly. If timers fire in bursts, look for event-loop blocking or a process that slept under container CPU throttling.

Field notes

  • Event-loop ordering is deterministic within a state, but application state changes from tick to tick; do not build correctness on fragile ordering.
  • A timer interval can drift heavily under load. Use a scheduler that measures wall-clock deadlines if exact spacing matters.
  • Closing sockets and servers runs close callbacks in a later phase; do not assume resources are gone the moment .close() returns.
  • The browser event loop and Node event loop are cousins, not twins. Transplanting browser intuition causes real design errors.

Was this lesson helpful?

Sign in to rate