Sub topic 5
How the Event Loop Schedules Callbacks
The previous chapter showed that an asynchronous callback runs "later." This chapter explains what decides when "later" is. You will learn how the call stack, the task queue, and the microtask queue work together, so you can predict the order of any mix of timers, Promise reactions, and I/O callbacks.
This chapter assumes you can write and run Node.js scripts and that you know the difference between synchronous and asynchronous callbacks. Promises appear only as a source of microtasks, so you need nothing more than Promise.resolve().then(...).
The Working Model
JavaScript runs your code on a single thread. At any moment it is running at most one piece of JavaScript. The host environment (the browser or Node.js) does the waiting: it counts down timers, watches network sockets, and reads files. When one of those operations finishes, the host does not interrupt your code. It puts your callback in a queue, and the event loop picks it up once the engine is free.
The model has four parts:
| Part | What it holds | Who adds to it |
|---|---|---|
| Call stack | The functions running right now, one frame per call | The engine, every time a function is called |
| Host APIs | Pending timers, I/O requests, event subscriptions | Your code, through `setTimeout`, `fs.readFile`, `addEventListener` |
| Task queue | Callbacks that are ready to run as separate tasks | The host, when a timer expires or I/O completes |
| Microtask queue | Small follow-up jobs that must run before the next task | Promise reactions, `queueMicrotask`, `MutationObserver` |
A task is one unit of work the event loop starts from an empty stack. Running your main script is a task. Each timer callback is a task. A microtask is a callback that runs as soon as the current task finishes and the stack is empty, before the event loop moves on.
The Loop Itself
The event loop repeats these steps:
- Take the oldest task from a task queue and run it until the call stack is empty.
- Run every microtask in the microtask queue. If a microtask schedules another microtask, run that one too. Continue until the queue is empty.
- In a browser, update rendering if it is time to do so.
- Go back to step 1. If no tasks are waiting, sleep until one arrives.
Two rules follow from this loop, and most ordering puzzles come down to them:
- A callback never interrupts running code. Nothing in a queue runs until the stack is empty.
- Each task runs alone, but all pending microtasks run together. The whole microtask queue is drained between two tasks.
Rule One: Nothing Interrupts the Stack
The delay you pass to setTimeout is a minimum. When the timer expires, the host only queues the callback. If the stack is busy, the callback waits.
const start = Date.now();
setTimeout(() => {
console.log('timer fired after', Date.now() - start, 'ms');
}, 100);
// Busy-wait for 500 ms, keeping the call stack occupied
while (Date.now() - start < 500) {}
console.log('loop done');
// loop done
// timer fired after 50x ms (about 500, never 100)The timer expired at 100 ms, but the main script was still running. The callback had to wait until the script task finished.
Browsers add their own limits on top of this. After five levels of nested setTimeout calls, browsers raise any delay below 4 ms to 4 ms. Background tabs may throttle timers to once per second or less. Do not use setTimeout for precise timing.
Rule Two: Microtasks Run Before the Next Task
A Promise reaction is a microtask, so it runs before any timer, even a timer with a zero delay:
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('microtask'));
console.log('sync');
// Output: sync, microtask, timeoutHere is the order step by step:
- The main script task runs.
setTimeoutgives a timer to the host..thenputs a reaction in the microtask queue because the Promise is already resolved.console.log('sync')runs. - The script task ends and the stack is empty. The loop drains the microtask queue and prints
microtask. - The loop takes the next task, which is the timer callback, and prints
timeout.
Microtasks That Schedule Microtasks
Microtasks added while the queue is draining run in the same drain. They join the back of the queue, and their position depends on when they are added:
setTimeout(() => console.log('timeout'), 0);
Promise.resolve()
.then(() => {
console.log('micro 1');
queueMicrotask(() => console.log('micro 3'));
})
.then(() => console.log('micro 2'));
console.log('sync');
// sync
// micro 1
// micro 3
// micro 2
// timeoutThe output says micro 3 before micro 2, which surprises many people. The second .then reaction is not queued when you write it. It is queued only when the Promise returned by the first .then resolves, and that happens when the first handler returns. By that time, the handler has already called queueMicrotask, so micro 3 is ahead in line.
queueMicrotask(fn) is the direct way to schedule a microtask without creating a Promise. It works in browsers and in Node.js. Later in this tutorial it is used to make a callback API consistently asynchronous.
Starving the Task Queue
Because the loop drains the entire microtask queue before taking another task, a microtask that keeps scheduling more microtasks blocks timers and I/O just like a while loop does:
let count = 0;
setTimeout(() => console.log('timer finally ran, count =', count), 0);
function spin() {
count++;
if (count < 1_000_000) queueMicrotask(spin);
}
queueMicrotask(spin);
// timer finally ran, count = 1000000The timer was ready almost at once, but it ran only after a million microtasks. If you replace queueMicrotask(spin) with setTimeout(spin, 0), each step becomes its own task, and other tasks can run between the steps. That is how you split long work into chunks so it does not starve the queue.
What Goes Where
| Scheduling API | Queue | Environment |
|---|---|---|
| `setTimeout`, `setInterval` | Task (timers) | Browser, Node.js |
| I/O callbacks (`fs.readFile`, sockets) | Task (poll phase in Node.js) | Node.js |
| DOM events, `MessageChannel` | Task | Browser |
| `setImmediate` | Task (check phase) | Node.js |
| `Promise.prototype.then`, `catch`, `finally`, `await` continuations | Microtask | Browser, Node.js |
| `queueMicrotask` | Microtask | Browser, Node.js |
| `process.nextTick` | Node.js next-tick queue, drained before promise microtasks | Node.js |
Node.js Specifics
Node.js uses the same two rules, but its event loop is split into phases, each with its own queue. In order: timers, pending callbacks, poll (most I/O callbacks), check (setImmediate), and close callbacks. Node.js drains microtasks after each individual callback, so the rule "microtasks run before the next task" still holds.
process.nextTick Runs Before Promise Microtasks
process.nextTick callbacks go into a separate queue. Node.js empties that queue before the promise microtask queue:
// Save as tick.js and run with: node tick.js
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');
// sync
// nextTick
// promiseThe Node.js documentation recommends queueMicrotask over process.nextTick for most new code. Recursive nextTick calls starve I/O in the same way recursive microtasks do.
setTimeout(fn, 0) Versus setImmediate
At the top level of a script, the relative order of these two is not guaranteed:
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
// Either order is possibleThe result depends on whether the 1 ms minimum timer has expired by the time the loop first enters the timers phase, and that depends on how fast the process starts. Inside an I/O callback the order is fixed, because the poll phase is followed by the check phase before the loop returns to the timers phase:
const fs = require('node:fs');
fs.readFile(__filename, () => {
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
});
// immediate
// timeout (always this order)Common Errors
- Treating the delay as exact.
setTimeout(fn, 1000)means "no sooner than 1000 ms." Measure elapsed time withDate.now()orperformance.now()instead of counting timer firings. - Expecting a zero-delay timer to run before a Promise. It never does. Promise reactions are microtasks.
- Assuming
setTimeout(fn, 0)lets rendering happen in between. It usually does in browsers, but only because rendering may happen between tasks. Microtasks never give way to rendering. - Spinning on microtasks. Recursive
queueMicrotask,process.nextTick, or Promise chains with no real waiting freeze timers and I/O. - Relying on
setTimeoutversussetImmediateorder at the top level. It is not guaranteed. Use one mechanism, or chain the calls explicitly.
Exercise
Predict the output: console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => { console.log(3); setTimeout(() => console.log(4), 0); }); queueMicrotask(() => console.log(5)); console.log(6);
Show answer
1, 6, 3, 5, 2, 4. The synchronous logs run first (1, 6). The microtask queue then holds the then-handler and the queueMicrotask callback in that order (3, 5). The handler that printed 3 scheduled timer 4 after timer 2 was already waiting, so the tasks print 2, then 4.
Exercise
A Node.js server calls setTimeout(sendHeartbeat, 1000), but logs show heartbeats arriving 1.8 seconds apart under load. The heartbeat function itself is fast. What is the most likely cause, and how do you confirm it?
Show answer
Some other callback is blocking the stack. That could be a long synchronous handler, such as parsing a large JSON body or running a CPU-heavy loop, or a long chain of microtasks. The timer expires on time but cannot run until the stack is free. Confirm it by measuring event loop delay, for example with perf_hooks.monitorEventLoopDelay(), or by profiling with node --cpu-prof to find the long-running function.
Exercise
Inside an fs.readFile callback in a CommonJS script, you schedule setImmediate(A), setTimeout(B, 0), process.nextTick(C), and Promise.resolve().then(D). In what order do A, B, C, and D run?
Show answer
C, D, A, B. After the readFile callback returns, Node.js drains the nextTick queue (C) and then the promise microtasks (D). The loop is in the poll phase, so the check phase comes next (A, from setImmediate). The timers phase comes after that (B).