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
setImmediateruns in the check phase
Deep dive: Request Lifecycle course: WSGI, ASGI and the Event Loop
More most-asked Node.js Developer questions
- What are streams in Node.js and what is backpressure?
- What are the differences between CommonJS and ES modules in Node.js?
- Walk through how an Express app handles a request, including errors from async handlers.
- What is the difference between `process.nextTick`, Promise microtasks, `setImmediate` and `setTimeout(fn, 0)`?
- How has asynchronous code evolved in Node.js: callbacks, Promises and async/await?
- What is Node.js and why is it well suited to I/O-heavy servers?
- Why is CPU-bound work a problem in Node.js and how do you handle it?
- How does middleware work in Express?