The event loop is the heart of Node.js. It's the loop inside libuv that decides which callback runs next. Once you understand it, you can predict the output of any async puzzle an interviewer throws at you, and you'll know why some code makes a server slow.
In this chapter you'll learn
- what the event loop is and what it's waiting for
- the six phases of each loop iteration, and what runs in each
- microtasks:
process.nextTickand Promises, and why they jump the queue - why the top-level order of
nextTickand Promises flips in ES Modules setImmediatevssetTimeout(0)- when the event loop waits, and when the Node.js process exits
- how to predict the output of tricky async code, step by step
Before you start: read Chapter 06: libuv & async IO (libuv) and Chapter 07: sync async, setTimeout Zero - Code (sync vs async in code). The examples are in Code/.
What is the event loop?
Remember the rule from Chapter 07: sync async, setTimeout Zero - Code: synchronous code runs first; callbacks run later, when the call stack is empty. The event loop is the part that makes "later" happen.
In simple terms, it's a loop that keeps asking:
"Is the call stack empty? Then, is any callback ready to run? If so, run it. Repeat."
The callbacks don't all wait in one line. libuv keeps separate queues for different kinds of callbacks, and the event loop visits them in a fixed order, called phases.

The six phases
Every turn of the event loop (one iteration, or tick) goes through these phases in order:
| # | Phase | What runs here |
|---|---|---|
| 1 | timers | setTimeout and setInterval callbacks whose time has come |
| 2 | pending callbacks | a few system-level I/O callbacks deferred from the last iteration (for example some TCP errors) |
| 3 | idle, prepare | internal libuv housekeeping; none of your code runs here |
| 4 | poll | I/O callbacks: a file was read, data arrived on a socket, a database replied. If nothing else is scheduled, the loop waits here for new events |
| 5 | check | setImmediate callbacks |
| 6 | close callbacks | close events, such as socket.on("close", ...) |
In day-to-day work you only deal with four of them: timers, poll, check and close. That's why you'll often see the event loop drawn with four phases (including in the original course lectures). It's a useful simplification, but in an interview, mention all six.
A few details worth knowing:
- In the timers phase, the expired callbacks are run directly, one after another. Each phase has its own queue, and the loop works through that queue while it's in the phase.
- The
setTimeoutdelay is a minimum: the callback runs in the first timers phase after the delay has passed, possibly later if the thread was busy. - The poll phase is where most of a server's work happens: incoming requests, database results and file reads all arrive here.
Microtasks: process.nextTick and Promises
There are two more queues, and they're special. They don't belong to any phase. Node.js empties them after every single callback (and after the main script finishes), before moving on:
- the
process.nextTickqueue, emptied completely first - the Promise microtask queue (
.then,.catch,awaitcontinuations), emptied completely next
So within any phase, the order is:
one callback → all nextTicks → all Promise callbacks → the next callback → ...
This is why a resolved Promise always beats a setTimeout(fn, 0): the Promise callback runs as soon as the current code finishes, without waiting for the event loop to reach the timers phase.
Before Node.js 11, microtasks ran only between phases, not after each callback. That's why some old blog posts show different output for the same code. Since Node.js 11, Node behaves like browsers: microtasks run after every callback.
process.nextTick vs Promise.then
Both are "run as soon as possible", but nextTick goes first:
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");sync
nextTick
promisesync
nextTick
promiseBecause the nextTick queue is emptied completely before anything else, a nextTick callback that keeps scheduling more nextTicks will starve the event loop: timers and I/O never get a turn. Prefer setImmediate or Promises unless you specifically need nextTick.
In ES Modules, the top-level order flips
Everything in this chapter's examples (and in Code/) is CommonJS. Run the same three lines as an ES Module (order.mjs, or a .js file with "type": "module") and you get a different answer:
// order.mjs
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");// order.mjs
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");sync
promise
nextTicksync
promise
nextTickWhy? An ES Module's top-level code is not run as a plain callback. Node runs module evaluation through Promises (that's what makes top-level await possible, see Chapter 05). So when your top-level code finishes, Node is already in the middle of emptying the Promise queue, and it keeps going: your .then callback runs first. The nextTick queue is checked only after the Promise queue is empty.
The flip only affects code at the top level of an ES Module. Inside any callback (a timer, an I/O callback, a request handler), the normal rule applies again in both systems: nextTick first, then Promises.
// still order.mjs
setTimeout(() => {
Promise.resolve().then(() => console.log("promise (in timer)"));
process.nextTick(() => console.log("nextTick (in timer)"));
}, 10);// still order.mjs
setTimeout(() => {
Promise.resolve().then(() => console.log("promise (in timer)"));
process.nextTick(() => console.log("nextTick (in timer)"));
}, 10);nextTick (in timer)
promise (in timer)nextTick (in timer)
promise (in timer)Interviewers usually mean CommonJS when they ask "nextTick or Promise first?". The strong answer: "nextTick first, after every callback. The one exception is the top level of an ES Module, where Promise callbacks run first, because module evaluation itself runs as part of the Promise queue."
setImmediate vs setTimeout(0)
Both mean "run soon", but in different phases: setTimeout in timers, setImmediate in check (right after poll).
Inside an I/O callback, the order is always the same: setImmediate first. The loop is in the poll phase, and check comes right after poll, while timers only come around in the next iteration.
At the top level of a script, the order is not guaranteed. It depends on whether the 1 ms timer has already expired when the loop starts, which depends on how busy your machine is. You'll usually see setTimeout first, but don't rely on it.
When does the loop wait, and when does Node.js exit?
When no callback is ready, the loop waits in the poll phase for new events, but only if there's something to wait for: a server listening for requests, an open socket, an active timer or an unfinished file read.
If nothing at all is pending, the loop ends and the process exits. That's why:
- a script with only
console.logfinishes immediately - a script that calls
app.listen(3000)keeps running until you stop it: the listening server is always "pending"
Predicting output, step by step
Let's put it all together with the course examples. Try to predict each output before reading it.
Example 1 (Eventloop2.js)
const fs = require("fs");
const a = 999;
setImmediate(() => console.log("setImmediate"));
Promise.resolve("promise").then(console.log);
fs.readFile("./file.txt", "utf-8", (err, data) => console.log(data));
setTimeout(() => console.log("setTimeout"), 0);
process.nextTick(() => console.log("process.nextTick"));
function printA() {
console.log("a:" + a);
}
printA();
console.log("last line of program");const fs = require("fs");
const a = 999;
setImmediate(() => console.log("setImmediate"));
Promise.resolve("promise").then(console.log);
fs.readFile("./file.txt", "utf-8", (err, data) => console.log(data));
setTimeout(() => console.log("setTimeout"), 0);
process.nextTick(() => console.log("process.nextTick"));
function printA() {
console.log("a:" + a);
}
printA();
console.log("last line of program");Output:
a:999
last line of program
process.nextTick
promise
setTimeout
setImmediate
<contents of file.txt>a:999
last line of program
process.nextTick
promise
setTimeout
setImmediate
<contents of file.txt>Step by step:
- Synchronous code first:
a:999, thenlast line of program. Meanwhile, the async calls only registered their callbacks. - Main script done → microtasks: nextTick queue (
process.nextTick), then Promise queue (promise). - Event loop, iteration 1 → timers: the 0 ms (= 1 ms) timer has expired →
setTimeout. - Poll: the file isn't read yet (reading a file takes several steps on the thread pool), so nothing to do here yet.
- Check:
setImmediate. - A later iteration → poll: the file read finishes and its callback prints the file contents.
Example 2 (Eventloop3.js): callbacks inside an I/O callback
const fs = require("fs");
setImmediate(() => console.log("1st setImmediate"));
setTimeout(() => console.log("1st timer"), 0);
Promise.resolve("promise").then(console.log);
fs.readFile("./file.txt", "utf-8", (err, data) => {
setTimeout(() => console.log("2nd timer"), 0);
process.nextTick(() => console.log("2nd nextTick"));
setImmediate(() => console.log("2nd setImmediate"));
console.log(data);
});
process.nextTick(() => console.log("1st nextTick"));
console.log("last line of program");const fs = require("fs");
setImmediate(() => console.log("1st setImmediate"));
setTimeout(() => console.log("1st timer"), 0);
Promise.resolve("promise").then(console.log);
fs.readFile("./file.txt", "utf-8", (err, data) => {
setTimeout(() => console.log("2nd timer"), 0);
process.nextTick(() => console.log("2nd nextTick"));
setImmediate(() => console.log("2nd setImmediate"));
console.log(data);
});
process.nextTick(() => console.log("1st nextTick"));
console.log("last line of program");Output:
last line of program
1st nextTick
promise
1st timer
1st setImmediate
<contents of file.txt>
2nd nextTick
2nd setImmediate
2nd timerlast line of program
1st nextTick
promise
1st timer
1st setImmediate
<contents of file.txt>
2nd nextTick
2nd setImmediate
2nd timerThe interesting part is the end. The readFile callback runs in the poll phase:
- Inside it,
console.log(data)is synchronous, so the file contents print first. - The callback finishes → microtasks run →
2nd nextTick. - The loop moves from poll to check →
2nd setImmediate. - Only in the next iteration does the loop reach timers →
2nd timer.
That's the rule from earlier: inside an I/O callback, setImmediate always beats setTimeout(0).
Example 3 (Eventloop4.js): nested nextTick
const fs = require("fs");
setImmediate(() => console.log("setImmediate"));
setTimeout(() => console.log("setTimeout"));
Promise.resolve("Promise").then(console.log);
fs.readFile("./file.txt", "utf-8", (err, data) => console.log(data));
process.nextTick(() => {
process.nextTick(() => console.log("inner nextTick"));
console.log("process.nextTick");
});
console.log("last line of program");const fs = require("fs");
setImmediate(() => console.log("setImmediate"));
setTimeout(() => console.log("setTimeout"));
Promise.resolve("Promise").then(console.log);
fs.readFile("./file.txt", "utf-8", (err, data) => console.log(data));
process.nextTick(() => {
process.nextTick(() => console.log("inner nextTick"));
console.log("process.nextTick");
});
console.log("last line of program");Output:
last line of program
process.nextTick
inner nextTick
Promise
setTimeout
setImmediate
<contents of file.txt>last line of program
process.nextTick
inner nextTick
Promise
setTimeout
setImmediate
<contents of file.txt>The inner nextTick is added to the nextTick queue while that queue is being emptied, so it runs immediately after, still before the Promise. The whole nextTick queue, including newly added items, is drained before the Promise queue starts.
Common mistakes
- Saying "Promises are part of the event loop phases." They're microtasks, run between callbacks, not in a phase.
- Assuming
setTimeout(fn, 0)vssetImmediatealways has the same order. Only inside I/O callbacks is it guaranteed. - Blocking the loop. While a callback runs a long loop, no other callback in any phase can run. Chapter 10: Thread Pool in libuv covers how to avoid it.
- Recursive
process.nextTickthat starves I/O. - Predicting top-level output without checking the module type. At the top level of an ES Module, Promise callbacks run before
nextTickcallbacks.
Key takeaways
- The event loop is libuv's loop that picks the next callback to run, phase by phase.
- Six phases: timers → pending callbacks → idle/prepare → poll → check → close callbacks.
- Microtasks (
process.nextTickfirst, then Promises) run after every callback, before the loop moves on. - Exception: at the top level of an ES Module, Promise callbacks run before
nextTick, because module evaluation runs as part of the Promise queue. setImmediateruns in check, right after poll; inside I/O callbacks it always beatssetTimeout(0).- The loop waits in poll only while something is pending; otherwise the process exits.
- Predict output as: sync → nextTick → Promises → timers → poll (I/O) → check → close, then repeat.
Interview questions
Q1. What is the event loop in Node.js?
The event loop is a loop, provided by libuv, that lets Node.js perform non-blocking I/O on a single JavaScript thread. When the call stack is empty, it goes through its phases (timers, pending callbacks, idle/prepare, poll, check, close) and runs the callbacks that are ready in each one. Between callbacks it drains the process.nextTick and Promise microtask queues.
Q2. List the phases of the event loop.
- Timers:
setTimeout/setIntervalcallbacks. 2. Pending callbacks: deferred system I/O callbacks. 3. Idle, prepare: internal. 4. Poll: I/O callbacks; waits for new events. 5. Check:setImmediatecallbacks. 6. Close callbacks: e.g.socket.on('close').
Q3. What's the difference between process.nextTick() and setImmediate()?
process.nextTick callbacks run immediately after the current operation, before the event loop continues (they're microtasks, and run even before Promise callbacks). setImmediate callbacks run in the check phase of the event loop, after I/O polling. The names are confusingly swapped: nextTick is the more "immediate" one.
Q4. What is the output, and why?
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("tick"));
Promise.resolve().then(() => console.log("promise"));
console.log("sync");setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("tick"));
Promise.resolve().then(() => console.log("promise"));
console.log("sync");sync, tick, promise, then timeout and immediate, whose order at the top level is not guaranteed (usually timeout first). Sync code runs first; then nextTick, then Promises; then the event loop reaches timers and check.
That's for a CommonJS file. As an ES Module the output starts sync, promise, tick: top-level module code runs as part of the Promise queue, so Node finishes the Promise callbacks before it looks at the nextTick queue.
Q5. Why does setImmediate always run before setTimeout(0) inside an I/O callback?
I/O callbacks run in the poll phase. The next phase after poll is check, where setImmediate callbacks run. Timers are only checked at the start of the next iteration. So from inside an I/O callback, setImmediate always comes first.
Q6. What are microtasks and macrotasks?
Macrotasks are callbacks scheduled into event loop phases: timers, I/O callbacks, setImmediate. Microtasks are Promise callbacks (and, in Node, process.nextTick, which has its own higher-priority queue). After every macrotask, all pending microtasks are run before the next macrotask.
Q7. When does a Node.js process exit on its own?
When the event loop has nothing left to do: no pending timers, no open sockets or servers, no I/O in progress and no queued callbacks. A running HTTP server keeps the loop alive, which is why server processes don't exit.
Q8. What does "blocking the event loop" mean?
It means running synchronous code long enough that the event loop can't move on: a huge loop, a sync file read, heavy JSON parsing or a slow regular expression. While it runs, no timers fire and no requests are handled, so the whole server freezes. The fix is to keep callbacks short, use async APIs, and move CPU-heavy work to worker threads (Chapter 10: Thread Pool in libuv).
Q9. Why does Promise.then run before process.nextTick at the top level of an .mjs file?
Because ES Modules are evaluated asynchronously: Node runs a module's top-level code through Promises (which is what allows top-level await). When that code finishes, Node is already draining the Promise microtask queue, so newly queued .then callbacks run in that same drain. The nextTick queue is processed only after it. In CommonJS, the main script runs as plain synchronous code, so the normal rule applies: nextTick queue first, then Promises. Inside callbacks (timers, I/O) both module types follow the normal rule.
What's next
You've seen file reads finish "later" in the poll phase. But who actually reads the file while JavaScript keeps going? And why don't 10,000 open network connections need 10,000 threads? Chapter 10: Thread Pool in libuv answers both: the libuv thread pool and the OS's epoll/kqueue.