The event loop
JavaScript runs on a single thread: it can only do one thing at a time. Yet it handles thousands of network requests, timers and clicks. The secret is the event loop. Understanding it explains "weird" output order, frozen pages, and how Node.js scales.
The pieces
- Call stack: the function that's running right now, plus whoever called it.
- Web APIs / Node APIs: timers, network and file I/O handled outside your JavaScript.
- Task queue (macrotasks): callbacks from
setTimeout, I/O and UI events. - Microtask queue: promise callbacks (
.then,awaitcontinuations) andqueueMicrotask.
The loop: run everything on the stack → then run all microtasks → then take one task → repeat.
Predict the output
Before pressing Run, write down the order you expect.
Why:
AandFare synchronous, so they run first.CandEare microtasks; they run as soon as the stack is empty.Dwas queued whenCfinished, so it runs right after.Bis a task. Even with a0ms delay, it waits until every microtask is done.
await is just a microtask
Everything after await is scheduled as a microtask. Microtasks run in the order they were queued, and all of them run before the setTimeout task.
Blocking the loop
Since there's one thread, long synchronous work blocks everything: timers, clicks and rendering.
In a browser, this would freeze the page. In a Node.js server, every user would wait.
How pros avoid blocking
- Split work into chunks and yield with
setTimeout/awaitbetween them. - Move heavy computation to a Web Worker (browser) or worker thread (Node). The code editors on this site do exactly that!
- Use async I/O APIs, never sync ones like
fs.readFileSyncinside a server request.
Microtask starvation
Because the loop drains all microtasks before the next task, a microtask that keeps scheduling more microtasks will starve timers forever. Recursive setTimeout doesn't have this problem.
Practice
Predict the exact output order, then run it to check.
1.Which runs first after the current script finishes: a resolved promise's .then or a setTimeout(fn, 0)?
2.Why is a long synchronous loop bad in a Node.js server?