The Node.js event loop, libuv, phases, and browser differences
🎯 Introduction
By the end of this article, you will understand how asynchronous results return to JavaScript and how Node.js scheduling differs from browser scheduling.
🧱 The event loop decides when subsequent code runs
The event loop repeatedly checks for ready tasks and schedules their callbacks. Completed file operations, incoming network data, and timers that reach their waiting threshold all need to hand work back to JavaScript.
Node.js uses libuv for low-level scheduling and some I/O capabilities. It is an internal library and requires no separate project import. V8 executes JavaScript; libuv's scheduling allows asynchronous work to progress.
A ready callback does not execute immediately. If the main thread is running other JavaScript, it must wait for that execution to finish. This explains timers that have reached their delay but print nothing yet, or completed reads whose callbacks are still waiting.
🧭 Phases determine when categories of callbacks run
File read callbacks, setImmediate callbacks, and timers do not share one queue that runs in registration order. Node.js handles them in separate stages called phases. Understanding phases explains callback order and prevents confusing “registered first” with “executed first.”
First connect three phase names to their work:
| Phase | Work handled | Corresponding code |
|---|---|---|
| poll | Ready notifications for file, network, and other I/O | File read completion callbacks |
| check | Callbacks scheduled with setImmediate | Functions passed to setImmediate |
| timers | Timer callbacks whose waiting thresholds have been reached | Functions passed to setTimeout and setInterval |
Node.js advances through phases automatically; you do not invoke them manually. The following only examines which of two callbacks registered after a file read runs first.
Observe file read completion first
Prepare note.txt containing hello and create phases.mjs:
import fs from 'node:fs'
fs.readFile('note.txt', 'utf8', (error, text) => {
if (error) {
console.error(error.code)
process.exitCode = 1
return
}
console.log('Read complete:', text)
})
Run node phases.mjs to print Read complete: hello. Once the underlying read finishes, Node.js executes this callback while handling I/O notifications. That is the kind of work associated with poll; you do not manually read the disk in that phase.
Schedule follow-up work inside the read callback
Append these three lines after console.log inside the callback above:
setTimeout(() => console.log('Timer callback'), 0)
setImmediate(() => console.log('Immediate callback'))
console.log('Current read callback ending')
Run it again to see:
Read complete: hello
Current read callback ending
Immediate callback
Timer callback
The current read callback finishes first. Then check runs the immediate callback, and the timer runs at its later scheduling opportunity. Registering timeout first therefore does not make it execute first. The condition is that both are registered within the same I/O callback. Do not apply this result to top-level code.
Apply this when writing code
- Process file contents directly in the read callback rather than guessing read completion with a timer.
- setImmediate inside an I/O callback schedules later work; it waits for the current callback to finish rather than interrupting it.
- If a timer is overdue, check for long-running JavaScript. Reaching a timer threshold does not interrupt current code.
These three phases are only the parts needed here, not the complete event loop. Promises and nextTick also affect order, so this table cannot predict every asynchronous program.
🧩 Microtasks are separate from these regular phases
Microtasks are short tasks processed with priority at specific checkpoints after current work finishes. Promise .then callbacks are microtasks. Node.js also has a dedicated queue for process.nextTick.
These queues affect when execution returns to regular event loop phases. The categories “timers, files, immediate callbacks” alone cannot predict all output. The next article continues with ESM examples to compare ordering.
⚖️ How this differs from the browser event loop
Browsers also execute JavaScript and process microtasks, while coordinating page clicks, style calculation, and rendering. Node.js has no page rendering. It primarily handles files, networking, and timers, and provides its own scheduling APIs.
Both follow the same principle: an ordinary asynchronous callback cannot arbitrarily interrupt synchronous JavaScript. They differ in task sources and scheduling opportunities. Browser rendering timing is not a Node.js event loop phase.
❓ Questions and answers
Q1: Does every iteration run callbacks in every phase?
No. Some phases have no ready work and produce no visible output.
Q2: Can a callback run immediately when a file operation finishes?
Current JavaScript must yield execution, and the appropriate scheduling opportunity must arrive.
Q3: Does the event loop execute expensive work itself?
Callback JavaScript still runs on its corresponding thread. Expensive callbacks delay subsequent scheduling.
🧪 Exercise
Swap the registration order of setTimeout and setImmediate inside the read callback and run it again. Check whether the output order changes and explain why registration order does not imply execution order.
// Write your code here
🎉 Try these techniques with your own examples!
