Back to results for “Debugging”
Node.js › Event Loop & Non-blocking IO

What are the distinct phases of the Node.js event loop, and what kind of callbacks does each phase execute?

Advanced

Answer

The event loop cycles through several phases each iteration: timers (executes callbacks scheduled by setTimeout/setInterval whose time has elapsed), pending callbacks (certain system-level callbacks deferred from the previous cycle), poll (retrieves new I/O events and executes their callbacks, and is where the loop will block waiting for new events if there's nothing else to do), check (executes setImmediate() callbacks), and close callbacks (handles cleanup for closed connections/handles) -- with microtasks (process.nextTick and Promise callbacks) draining completely between each of these phases.
setTimeout(() => console.log('timers phase'), 0);
setImmediate(() => console.log('check phase'));

fs.readFile(__filename, () => {
  setTimeout(() => console.log('timer from within poll'), 0);
  setImmediate(() => console.log('immediate from within poll')); // guaranteed to run first here
});
Real-world example A developer debugging unexpected ordering between a setTimeout(fn, 0) and a setImmediate() callback learns that their relative order at the top level of a script isn't strictly guaranteed, but inside an I/O callback (within the poll phase), setImmediate() is always guaranteed to fire before a zero-delay setTimeout, since the check phase directly follows poll.

Common follow-ups: Why is the ordering between setTimeout(fn, 0) and setImmediate() considered non-deterministic at the top level of a script but deterministic inside an I/O callback?;What specifically happens during the poll phase when there's no pending I/O and no timers scheduled?