Node.js Developer interview question · Most asked

Explain the phases of the Node.js event loop.

Summary

Each loop iteration runs these phases in order: timers (setTimeout/setInterval callbacks), pending callbacks (some system errors), idle/prepare (internal), poll (retrieve new I/O events and run I/O callbacks; may block waiting), check (setImmediate callbacks) and close callbacks (socket.on('close')).

Longer Answer

Between each callback, Node drains the process.nextTick queue and then the Promise microtask queue. The loop exits when there are no more pending handles or requests. Understanding phases explains ordering puzzles, e.g. setImmediate always runs before setTimeout(0) when both are scheduled from within an I/O callback.

Code Example

const fs = require("node:fs");

fs.readFile(__filename, () => {
  setTimeout(() => console.log("timeout"), 0);
  setImmediate(() => console.log("immediate"));
  process.nextTick(() => console.log("nextTick"));
  Promise.resolve().then(() => console.log("promise"));
});
// nextTick, promise, immediate, timeout

Key Points

  • timers → pending → poll → check → close
  • nextTick and microtasks drain between callbacks
  • Poll phase waits for I/O
  • setImmediate runs in the check phase

Deep dive: Request Lifecycle course: WSGI, ASGI and the Event Loop

More most-asked Node.js Developer questions

← All Node.js Developer questions