Open this lesson in your favourite AI. It'll walk you through the why, explain the demo, and quiz you on the try-it list.
The Node event loop has phases (timers, pending callbacks, poll, check, close) and TWO microtask queues (Promise jobs, process.nextTick) that run between phases. The detailed mechanics matter the moment you write setTimeout(fn, 0) and find it doesn't run before a Promise.then callback. The subtle ordering of setImmediate, setTimeout(0), Promise.then, and process.nextTick is the single most-asked Node interview question — and knowing it actually saves you from real bugs.
The Node.js event loop processes callbacks in a specific order across phases — timers, pending I/O, idle/prepare, poll, check (setImmediate), and close callbacks — and process.nextTick runs before any of them at the end of each operation. Predicting the execution order of mixed setTimeout, setImmediate, Promise.resolve, and process.nextTick calls is a common interview exercise precisely because it forces you to reason about each queue separately rather than treating async as a monolith. Getting it right without running the code means you genuinely understand which callbacks are microtasks versus macrotasks and why that distinction matters for performance.
console.log("1");
setTimeout(() => console.log("2"), 0);
setImmediate(() => console.log("3"));
Promise.resolve().then(() => console.log("4"));
process.nextTick(() => console.log("5"));
console.log("6");
// actual output:
// 1
// 6
// 5 <- process.nextTick — highest-priority microtask
// 4 <- Promise.then — lower microtask
// 2 or 3 <- setTimeout vs setImmediate, order is non-deterministic at top level
// (the other one)
// the rule:
// 1. Sync code finishes.
// 2. process.nextTick queue drains (highest priority).
// 3. Promise microtask queue drains.
// 4. Event loop advances one phase.
// 5. Repeat 2-4.node main.js5 (nextTick) prints before 4 (Promise) — both before any timer callback.setImmediate and setTimeout(0) inside a fs.readFile callback. There setImmediate is guaranteed to run before setTimeout(0). Test it.setImmediate to chunk the work — it yields back.node --inspect and use Chrome DevTools to view the event-loop tab while a real workload runs.Use these three in order. Each builds on the one before.
In one paragraph, explain what the Node event loop is — phases vs microtasks vs callbacks.
Walk me through the order of execution: sync, process.nextTick, Promise.then, setTimeout, setImmediate. Why is process.nextTick highest priority?
On a hot request handler, I see latency tail. The CPU is fine. What event-loop tools do I reach for — `perf_hooks.monitorEventLoopDelay`, `--prof`, `clinic.js doctor`?