The event loop, tasks and microtasks
JavaScript runs one piece of code at a time and picks the next piece from queues. Learn the order: synchronous code, then every microtask, then the next task.
Node and browsers run JavaScript on one thread with an event loop. The loop takes one task from a queue, runs it to completion, then drains the microtask queue completely, then takes the next task. Nothing interrupts running code. Concurrency comes from interleaving many short tasks, not from running them at the same moment.
- Tasks (macrotasks): timer callbacks, I/O callbacks,
setImmediate, and in browsers, events and messages. - Microtasks: promise reactions (
.then, the code after anawait) andqueueMicrotask. In Node,process.nextTickcallbacks run even before promise microtasks.
Run five lines and predict the output
1console.log("A"); 2setTimeout(() => console.log("B"), 0); 3Promise.resolve().then(() => console.log("C")); 4queueMicrotask(() => console.log("D")); 5console.log("E");
- main script
…The whole script is one task. It runs to completion before anything else.
Node's loop phases
libuv runs Node's loop in phases: timers (expired setTimeout), pending callbacks, poll (wait for I/O and run its callbacks), check (setImmediate) and close callbacks. Microtasks drain between every callback. The poll phase is where the process sleeps in epoll_wait or kqueue when there is nothing to do.
// Process 100,000 items without freezing other requests
async function processAll(items: Item[]) {
for (let i = 0; i < items.length; i++) {
handle(items[i]);
if (i % 1000 === 0) {
// Yield to the event loop: a real task boundary, not a microtask
await new Promise((resolve) => setImmediate(resolve));
}
}
}
// Note: `await Promise.resolve()` would NOT yield to I/O.
// It only queues a microtask, which runs before any task.In browsers, scheduler.yield() serves the same purpose and keeps the task's priority.
Where you will meet it
React batches state updates and the browser paints between tasks. A chat UI that processes tokens in one long microtask chain cannot paint until it finishes (Module 11).
A Node server whose loop is blocked cannot answer its health check, so the orchestrator restarts it while it is merely busy.
perf_hooks.monitorEventLoopDelay() reports how late the loop runs callbacks. Alert on its p99, not CPU.
Check yourself
Answer out loud before you open each one.
What does await do relative to the event loop?
It suspends the async function and resumes it in a microtask once the awaited promise settles.
Why does setTimeout(fn, 0) run after a resolved promise's .then?
The timer callback is a task. All microtasks drain before the loop takes the next task.
How do you yield to I/O in the middle of a long loop in Node?
Await a task boundary such as setImmediate, not a resolved promise.
Try it
Add process.nextTick, setImmediate and setTimeout(..., 0) to the example, run it in Node, and explain the order. Then run it inside an I/O callback and see setImmediate beat the timer.