Three things that are always true
The foundation. Everything later is built on these.
Most explanations of the event loop open with a diagram of phases, and that is why the subject feels arbitrary: the phases are a consequence, and the diagram shows them without the reasons. This page starts one level lower, with three statements that hold with no “usually” attached. They describe the main thread of a Node process; a worker thread is simply a second, separate copy of everything here.
- Your JavaScript runs on one thread, one function at a time, and a function that has started runs to completion.
Nothing can pause it halfway through to run something else — not a timer, not an incoming request, not another callback.
- So a callback can only start when the call stack is empty.
This is the first fact seen from the other side. While any function is still running, starting a callback would mean interrupting it, and the first fact rules that out.
- Asynchronous work never waits in JavaScript. The waiting happens outside it, and what comes back is always a callback.
Waiting for a socket, a file or a clock is done by the operating system kernel or by a few C++ threads, and your code is handed a callback when it is over.
awaitlooks like waiting, but section 04 shows it is a callback too. The*Syncfunctions andAtomics.waitare not asynchronous: they really do wait, on the one thread, and fact 1 says what that costs — nothing else runs until they return.
Every other fact on this page is derived from those three. The map below shows how: each arrow means “follows from”. Click any amber box to jump to the section that derives it.
Before building anything, it is worth feeling the first fact. Below, a script sets a timer for 10 ms, a request is due to arrive at 30 ms, and then the script runs a busy loop. Drag how long that loop runs.
The dashed lines mark when the timer and the request wanted to run; the amber dots mark when they actually could. Measured on Node 24, a 200 ms busy loop made a 10 ms timer run at 202 ms.
Nothing here is late because Node is slow. The timer’s callback is a callback (fact 3), a callback starts only on an empty stack (fact 2), and the stack is not empty until the loop finishes (fact 1). So the delay you pass to setTimeout is a minimum, never an appointment. Node’s own guide says a timer specifies “the threshold after which a provided callback may be executed rather than the exact time”. You have just seen why it has to.
If you had to build it
Three drafts of a loop, each fixing the problem in the one before — then the real one.
Put facts 2 and 3 side by side. Callbacks arrive from outside, and they may only start when nothing else is running. So something has to hold them until the stack is empty and then start them one at a time. The simplest code that does that:
// draft 1 while (true) { const callback = queue.shift(); if (callback) callback(); }
It is correct and useless. With nothing to do, it spins at 100% CPU asking an empty queue whether anything has changed. What it should do is sleep until there is something to do, and the only party who knows when a socket has data is the kernel. Every operating system offers a way to say “here are all my sockets; put me to sleep until something happens”. On Linux it is epoll_wait and on macOS kqueue, which report sockets that are ready; Windows does the same job with I/O completion ports, which report operations that have finished.
// draft 2 while (true) { const ready = waitForIO(Infinity); // sleeps inside the kernel for (const event of ready) event.callback(); }
Now it sleeps properly — and never wakes up for a timer, because a timer is not a socket. Nobody is going to make a file descriptor ready at exactly 10 ms. The fix is to stop sleeping forever: before going to sleep, look at the nearest timer and sleep only until then.
// draft 3 while (true) { const timeout = nearestTimer() ? nearestTimer().due - now() : Infinity; for (const event of waitForIO(timeout)) event.callback(); for (const timer of timersDueBy(now())) timer.callback(); }
That is nearly the real thing. Two more needs finish it. Code sometimes wants to run “right after this round of I/O”, without faking it with a timer — so there is a queue checked straight after the wait. And a handle being closed has to let everything finish using it before its close callback runs — so that gets a slot of its own near the end. Give each step a name and you have what libuv, the C library underneath Node, actually runs. This is uv_run from libuv 1.50:
int uv_run(uv_loop_t* loop, uv_run_mode mode) {
r = uv__loop_alive(loop);
if (mode == UV_RUN_DEFAULT && r != 0 && loop->stop_flag == 0) {
uv__update_time(loop);
uv__run_timers(loop); /* once, before the loop starts */
}
while (r != 0 && loop->stop_flag == 0) {
uv__run_pending(loop); /* pending callbacks */
uv__run_idle(loop); /* idle */
uv__run_prepare(loop); /* prepare */
timeout = uv__backend_timeout(loop);
uv__io_poll(loop, timeout); /* poll: the only place it sleeps */
uv__run_check(loop); /* check: setImmediate */
uv__run_closing_handles(loop); /* close callbacks */
uv__update_time(loop);
uv__run_timers(loop); /* timers */
r = uv__loop_alive(loop);
}
return r;
}
libuv v1.50.0, src/unix/core.c — trimmed of metrics bookkeeping, run-mode checks and a bounded re-run of pending callbacks after poll.
Draft 3 is visibly still in there: wait with a timeout, handle I/O, run due timers. Node itself adds almost nothing around it. Its SpinEventLoopInternal calls uv_run(loop, UV_RUN_DEFAULT) in a loop and stops when nothing is left — after giving 'beforeExit' listeners one chance to schedule more. “The event loop” is not a JavaScript feature at all. It is this C function, and your callbacks are what it calls.
One line deserves a second look: r = uv__loop_alive(loop). The loop keeps going while anything could still produce a callback — an active timer, a listening server, a file read in flight. When nothing can, uv_run returns and the process exits. That is why a script with a setInterval never exits, and why timer.unref() exists: it tells the loop not to count that timer.
The phases, and how long poll sleeps
Six stops, each one a queue of one kind of callback.
Each named step in that loop is called a phase, and each phase runs one kind of callback. In the order the loop visits them:
| Phase | What runs there | Scheduled by |
|---|---|---|
| pending | A few I/O callbacks libuv held back from the previous iteration — Node’s guide gives some TCP errors as the example. | internal |
| idle, prepare | libuv’s own hooks. None of your callbacks run here, but Node uses idle for one trick you will meet below. | internal |
| poll | I/O callbacks: data arrived on a socket, a connection opened, a file read finished. The only phase that can sleep. | fs, net, http… |
| check | Immediates — the “right after this round of I/O” queue from section 02. | setImmediate |
| close | Close callbacks of handles closed abruptly, such as a destroyed socket’s 'close' event. | socket.destroy() |
| timers | Callbacks of timers whose delay has passed, earliest first. | setTimeout, setInterval |
Older articles put timers at the top of the loop. That was true before libuv 1.45. Since libuv 1.45 (Node 20), timers run after close callbacks in every iteration, plus one extra pass before the loop starts for backwards compatibility. The table and the code above follow that order, and Node’s own guide now describes it the same way.
How long does poll sleep?
Poll is the only place the loop can block, so the most consequential decision in the whole loop is draft 3’s: how long to sleep. libuv makes it in uv__backend_timeout. The rule reads: sleep until the nearest timer, unless there is a reason not to sleep at all.
One line of it is a detail you would not guess. Node runs immediates from a check handle, and a check handle has no say in how long poll sleeps. So while an immediate is queued — one that keeps the process alive; an unref()ed immediate does not count — Node also starts an empty idle handle whose only purpose is to make this function return 0. Node’s source (src/env.cc) says it plainly: “Idle handle is needed only to stop the event loop from blocking in poll.”
Set up the loop’s state. The lines of libuv’s real code that decide the answer light up: amber for the path taken, brown for the condition that failed.
Now watch every phase fire in one program. A TCP connection completes, so its callback runs in poll. That callback queues one thing for each of the other kinds, then destroys the socket. Press step, or run it.
The output comes out as nextTick, immediate, socket closed, timeout. That is exactly the order of the loop starting from poll: first the nextTick queue (it is not a phase, and section 04 explains why it jumps in first), then check, then close, then timers. In the simulator the timer is not yet due at the end of the first iteration, so poll sleeps one millisecond and the second iteration runs it. On a real machine that millisecond may already have passed; the output is the same either way.
Between every callback
Two queues that are not phases at all.
Promises need something the loop does not have. The language specification requires a .then callback to run after the current code finishes, yet it should run as soon as possible — not after the next round of I/O. JavaScript engines provide that as the microtask queue. V8 holds the queue, but Node sets V8’s microtask policy to explicit and decides itself when to empty it: after each callback returns. queueMicrotask puts a function on that same queue. Node also has an older queue of its own, for process.nextTick.
Neither queue is a phase. Both are emptied after every single callback the loop runs — after each timer, each immediate, each I/O callback — not once per phase. (Before Node 11, a whole batch of timers or immediates ran before the queues were emptied. Since Node 11, “nextTick queue will be run after each immediate and timer”.) Here is the function that empties them, from Node 24:
function processTicksAndRejections() { let tock; do { while ((tock = queue.shift()) !== null) { // … run tock.callback(...tock.args) } runMicrotasks(); } while (!queue.isEmpty() || processPromiseRejections()); }
Node v24.0.0, lib/internal/process/task_queues.js — trimmed of async-hooks bookkeeping.
Three rules fall straight out of those lines, and together they predict every ordering in the sandbox below:
- All nextTicks before any microtask. The inner
whileempties the nextTick queue first — including ticks added while it runs. - Microtasks run until the queue is empty.
runMicrotasks()hands over to V8, which runs every microtask, including ones queued by other microtasks. - Then check again. If a microtask queued a nextTick, the
do…whilegoes round once more.
And fact 3 promised that await is a callback too. It is: when an async function reaches await, it returns to its caller, and the rest of the function is queued as a microtask once the awaited value settles. Pick async / await below and watch it split in two.
queueMicrotask and Promise.resolve().then share V8’s single queue, so between those two the order is plain first in, first out. process.nextTick is the one that cuts in line — in this CommonJS file. Section 06 shows the one place where it does not.
setTimeout(0) or setImmediate?
A race you can now call.
Here is the classic question. In a main script, which of these prints first?
setTimeout(() => console.log('timeout'), 0); setImmediate(() => console.log('immediate'));
Node’s guide says the order “is non-deterministic, as it is bound by the performance of the process”. That is true, and with sections 02 and 03 in hand you can say exactly what it depends on:
setTimeout(cb, 0)issetTimeout(cb, 1). Node’s docs: when the delay is “less than 1 or NaN, the delay will be set to 1”. So the timer is due one millisecond after it was created.- The script finishes, and
uv_runstarts with its one extra timers pass. It reads the clock and runs any timer that is already due. (This is a CommonJS script. An ES module works differently, and section 06 shows why.) - If a millisecond has passed by then,
timeoutprints first. If not, the timer is not due yet. The loop moves on to poll, which does not sleep because an immediate is waiting, then to check — andimmediateprints first. The timer runs at the end of that iteration or the next.
So the race is really: did a millisecond pass between the setTimeout call and the loop’s first look at the clock? On a fast machine it usually has not. Measured on Node 24.0.0:
| Where the two calls are | Runs | immediate first | timeout first |
|---|---|---|---|
| main script | 1000 | 964 | 36 |
| main script + 2 ms busy loop | 100 | 0 | 100 |
| inside an fs.readFile callback | 50 | 50 | 0 |
| top level of an ES module + 20 ms busy loop | 30 | 30 | 0 |
The last two rows need no clock at all. An I/O callback runs in poll. The next phase is check, and timers come after that — so an immediate queued inside I/O always beats any timer, however long the callback takes. The ES module row is the same case in disguise: section 06 shows that a module’s top level runs from poll too. The simulator below uses a CommonJS script and lets you set the one thing a real machine decides for you: whether the script took at least a millisecond.
The same code, as an ES module
Why the first two lines of output swap places.
process.nextTick(() => console.log('nextTick')); Promise.resolve().then(() => console.log('promise'));
Saved as .cjs, this prints nextTick then promise. Saved as .mjs, it prints promise then nextTick — in every measured run (50 as CommonJS, 20 as ESM). Rule 1 of section 04 said nextTicks go first. Why does that stop holding?
Rule 1 describes what happens when Node empties the queues, and the question is who gets there first. A CommonJS main script is run synchronously by Node, before the loop starts. When it returns, Node empties the queues, nextTick first.
An ES module is loaded by Node’s module loader, and the loader is asynchronous all the way down. For a file: URL it reads the source with await readFileAsync(url) from fs/promises (lib/internal/modules/esm/load.js). That is a thread-pool read, so the loop has to be running to deliver the result. You can see it: performance.nodeTiming.loopStart is -1 while a CommonJS main script runs, and already 12.5 ms while an ES module’s top level runs. By the time your first line executes, the read has come back through poll, the loader’s promise has resolved, and your module is being evaluated in the microtasks after that callback. Here is the real stack when the first line of an .mjs file runs:
at file:///…/esm-stack.mjs:1:13 at ModuleJob.run (node:internal/modules/esm/module_job:303:25) at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:663:26) at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:99:5)
Those async frames mean your module body is running inside a microtask. When the body ends, V8 is still in the middle of emptying the microtask queue, so it carries on through the promise callbacks you just queued — and anything those queue — before control ever returns to Node’s nextTick queue. Node 24’s API docs say the same: “since ESM modules are processed already as part of the microtask queue, there queueMicrotask() callbacks are always executed before process.nextTick() ones”. You can measure how complete that is. Queue one nextTick, then start a chain of 1000 steps, each queuing the next with a promise: in ESM the nextTick runs only after the whole chain has finished; in CommonJS it runs before the first promise callback.
Running from poll has a second consequence, and it closes the question from section 05. At the top level of an ES module there is no race between setTimeout(0) and setImmediate: the loop is already in poll, check comes next, and timers come after. Put a 20 ms busy loop after both calls and immediate still prints first, 30 runs out of 30. Switch the simulator to ES module and step through the start: the pre-loop timers pass and the first poll happen before your first line.
Both differences apply only to the top level of an ES module. Inside a timer, an immediate or an I/O callback, the callback was started by Node, so an ES module behaves exactly like CommonJS there: nextTicks first. The useful lesson is not which one wins, but that code whose correctness depends on the order between nextTick and promises is fragile.
Queues that never empty
The loop’s one fairness rule, and the two queues that ignore it.
Put two earlier facts next to each other. Section 04: the nextTick and microtask queues are emptied until empty, including items added while emptying. Section 03: the loop only moves to its next phase once that emptying is done. So a nextTick callback that queues another nextTick never lets the emptying finish, and the loop never reaches any phase at all. No timer, no immediate, no I/O — the process is alive and deaf.
The check phase is built differently. It runs only the immediates that were queued before the phase began; anything queued while it runs waits for the next iteration. A self-repeating setImmediate therefore gives every other phase a turn, each time around. Measured on Node 24.0.0. The nextTick and promise chains ran for 300 ms each; the setImmediate chain ran until a 5 ms timer fired:
| A callback that re-queues itself with | Iterations | A timer queued before the chain ran after |
|---|---|---|
| process.nextTick | 4,093,770 | 302 ms — when the chain stopped |
| Promise.resolve().then | 5,569,365 | 302 ms — when the chain stopped |
| setImmediate | 2,605 so far | 5 ms — on time (it was set for 5) |
That is the asymmetry the names hide: process.nextTick runs sooner than setImmediate. Node’s guide admits it — “In essence, the names should be swapped” — and explains that renaming them would break too much of npm. Its advice follows from everything above: use setImmediate when you want to yield to the loop, because only that one does.
Not everything happens on the loop
The four threads behind fs.
Fact 3 said waiting happens outside JavaScript. For sockets, the kernel does the waiting: one epoll_wait call on the loop thread can watch tens of thousands of connections. Files do not fit that model. epoll refuses regular files outright, and the older select and poll calls report a regular file as always ready, even when reading it will block on the disk. DNS lookups through getaddrinfo are plain blocking C calls. There is no “tell me when it’s ready” to wait on.
So libuv keeps a thread pool. Work that can only be done by blocking is handed to a pool thread; when it finishes, the result is posted back to the loop, and your callback runs in poll like any other I/O callback. The pool is global, holds 4 threads by default, and can be resized at startup with UV_THREADPOOL_SIZE (up to 1024). Node 24’s docs list what uses it:
- all
fsAPIs, other than the file watcher APIs and the explicitly synchronous ones - asynchronous crypto:
crypto.pbkdf2(),scrypt(),randomBytes(),randomFill(),generateKeyPair() dns.lookup()— whichhttp.get('https://some-host/')calls for you- all
zlibAPIs, other than the explicitly synchronous ones
Four threads is a queue, and a queue has consequences you can compute. Each job below is one crypto.pbkdf2 call that took 115 ms on the test machine.
One row per pool thread. A job that finds every thread busy waits in line and starts on the first one to free up. The bottom row is the loop thread: each tick is a callback landing in poll.
Measured on Node 24.0.0 on a 16-core machine: with the default pool, hashes 1–4 finished at 117–119 ms and hashes 5 and 6 at 232 and 235 ms. With UV_THREADPOOL_SIZE=2, they finished in pairs, at about 117, 233 and 350 ms. The fifth hash did not wait for a CPU — twelve cores were idle. It waited for a thread. The same queue is shared by every file read and every dns.lookup in the process, which is how a burst of password hashing can make unrelated file reads slow.
The whole page in six rules
Each one derived above; none needs memorising on its own.
- A delay is a minimum. A callback cannot start until the stack is empty, so any synchronous work delays every timer, request and callback behind it. 01
- One iteration is pending → poll → check → close → timers. Timers also get one pass before the loop starts. Poll sleeps until the nearest timer, and does not sleep at all while an immediate or a closing handle is waiting. 02 03
- After every callback: all nextTicks, then all microtasks, repeated until both are empty.
awaitis a microtask. 04 - Inside I/O,
setImmediatealways beatssetTimeout(0)— and the top level of an ES module counts as inside I/O, because it runs from poll. In a CommonJS main script, it depends on whether a millisecond passed first. At the top level of an ES module, promises also beat nextTick. 05 06 - To yield, use
setImmediate. A nextTick or promise that re-queues itself starves the whole loop. 07 - fs, dns.lookup, async crypto and zlib share four threads. Network sockets do not use them. 08
What this page leaves out
The simulators model the parts of the loop your code can observe, not all of libuv. Left out: Windows, where poll is built on I/O completion ports but the phase order is the same; worker threads, each with a loop and microtask queue of its own; how unhandled promise rejections are processed (the processPromiseRejections in that do…while); async_hooks and AsyncLocalStorage; child-process and signal handling; and the browser’s event loop, which has rendering steps and no setImmediate or process.nextTick. Timings are from one machine and will differ on yours. Orderings will not, except where this page says they depend on the clock.