The Event Loop Explained: How JavaScript Runs Async Code
JavaScript is single-threaded yet handles concurrency. Learn the call stack, task queues, microtasks, and why setTimeout has a minimum delay.
By Velloreth
The single-threaded puzzle
JavaScript is single-threaded. It has one call stack and executes one thing at a time. Yet a web page can fetch data, animate, respond to clicks, and run timers simultaneously.
The resolution is that JavaScript does not do those things itself. The runtime — the browser or Node — provides the concurrency, and the event loop coordinates it.
The model has four parts:
- Call stack — where function calls execute.
- Web APIs / Node APIs — where timers, network requests, and I/O actually run, off the main thread.
- Task queues — where completed callbacks wait.
- Event loop — which moves callbacks from the queues to the stack when it is empty.
The call stack
The call stack tracks where you are in the program. Each function call pushes a frame; each return pops one.
function a() { b(); }
function b() { c(); }
function c() { console.log('done'); }
a();
The stack grows as a calls b calls c, then unwinds. If it grows too deep, you get a stack overflow — which is exactly what happens with runaway recursion.
The stack is the reason JavaScript is single-threaded in the sense that matters: only one function is executing at any moment.
The event loop in action
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
The output is 1, 4, 3, 2. This surprises almost everyone the first time.
Here is why:
console.log('1')runs synchronously. Output:1.setTimeouthands the callback to the runtime, which starts a timer. The callback is queued as a macrotask.Promise.resolve().then(...)queues the callback as a microtask.console.log('4')runs synchronously. Output:4.- The synchronous code is done. The event loop drains the microtask queue first. Output:
3. - Then it takes the next macrotask. Output:
2.
The rule: microtasks before macrotasks, and the microtask queue drains completely before the next macrotask.
Microtasks vs macrotasks
| Microtasks | Macrotasks | |
|---|---|---|
| Sources | Promises, queueMicrotask, MutationObserver | setTimeout, setInterval, I/O, events |
| When they run | After the current task, before the next macrotask | One per event loop iteration |
| Queue behaviour | Entire queue drains | One task per iteration |
The distinction matters because a microtask can starve the event loop. If a microtask queues another microtask, the queue never empties and the next macrotask never runs.
// This hangs the page forever
function loop() {
Promise.resolve().then(loop);
}
loop();
The same code with setTimeout would not hang, because each iteration yields to the event loop.
Why setTimeout(fn, 0) is not immediate
setTimeout with a delay of 0 does not run the callback immediately. It queues a macrotask, which runs only after:
- The current synchronous code finishes.
- All pending microtasks drain.
- The browser has had a chance to render.
Browsers also clamp the delay. After five nested timers, the minimum becomes 4 milliseconds. In background tabs, timers are throttled to once per second or more.
So setTimeout(fn, 0) means “as soon as possible after the current work and all microtasks”, not “now”.
Blocking the event loop
Because there is one thread, long synchronous work blocks everything.
// Freezes the page for several seconds
function slowSum() {
let total = 0;
for (let i = 0; i < 10_000_000_000; i++) total += i;
return total;
}
While this runs, no clicks are handled, no timers fire, and nothing renders. The page is frozen.
The fixes:
Chunk the work. Break the loop and yield between chunks:
function chunkedSum(total, callback) {
let sum = 0;
let i = 0;
function step() {
const end = Math.min(i + 1_000_000, total);
for (; i < end; i++) sum += i;
if (i < total) setTimeout(step, 0);
else callback(sum);
}
step();
}
Move it off the main thread. A Web Worker runs in a separate thread:
const worker = new Worker('worker.js');
worker.postMessage({ n: 10_000_000_000 });
worker.onmessage = (e) => console.log(e.data);
Use an async API. fs.promises.readFile does not block; fs.readFileSync does.
Rendering and the event loop
In browsers, the event loop also handles rendering. The cycle is roughly:
- Run one macrotask.
- Drain the microtask queue.
- If needed, run
requestAnimationFramecallbacks. - Recalculate styles, layout, and paint.
- Repeat.
This is why requestAnimationFrame is the right place for animation: it runs just before the browser paints, so your changes are included in that frame.
function animate() {
element.style.transform = `translateX(${x++}px)`;
if (x < 100) requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Using setTimeout for animation instead produces jank, because the timing does not align with the render cycle.
The event loop in Node
Node’s event loop has distinct phases:
| Phase | Handles |
|---|---|
| Timers | setTimeout, setInterval |
| Pending callbacks | Deferred I/O callbacks |
| Poll | Retrieve new I/O events |
| Check | setImmediate callbacks |
| Close | Close event callbacks |
Node also has process.nextTick, which is not a microtask in the browser sense but runs before the microtask queue drains — it has the highest priority.
process.nextTick(() => console.log('nextTick'));
Promise.resolve().then(() => console.log('promise'));
setImmediate(() => console.log('immediate'));
The order is nextTick, promise, immediate. process.nextTick is the most immediate, and overusing it starves the event loop just as microtasks do.
Common misconceptions
“setTimeout(fn, 0) runs immediately.” It queues a macrotask. Microtasks run first.
“Promises are asynchronous.” The .then callback is asynchronous, but the promise executor runs synchronously:
console.log('a');
new Promise((resolve) => {
console.log('b'); // runs synchronously!
resolve();
});
console.log('c');
// a, b, c
“await blocks the thread.” It suspends the async function, not the program.
“JavaScript is multi-threaded because of workers.” Workers are separate threads with separate stacks. They communicate by message passing, not shared memory (except with SharedArrayBuffer).
“The event loop is part of the language.” It is part of the runtime. The language specification defines promises and jobs; the host defines the loop.
Practical guidance
- Keep synchronous work short. Anything over about 50 milliseconds is noticeable.
- Prefer async APIs over their sync counterparts in servers and browsers.
- Use Web Workers for CPU-heavy work.
- Use
requestAnimationFramefor visual updates. - Do not starve the microtask queue with recursive promise chains.
- Remember the ordering — sync, then microtasks, then macrotasks.
- Profile before optimising — the event loop is rarely the bottleneck until it is.
For the async patterns built on this, see promises vs async/await and callbacks explained. For the browser performance angle, improve inp core web vitals static site and how cdns actually work.
Quotable summary
JavaScript runs on a single thread with a call stack, and the event loop moves queued callbacks onto that stack whenever it is empty. Microtasks from promises run before macrotasks from timers and I/O, and the entire microtask queue drains before the next macrotask begins. setTimeout(fn, 0) queues a macrotask that runs after all pending microtasks and after the browser has had a chance to render, which is why it is not immediate. Blocking the call stack blocks rendering, input, and timers, so long synchronous work freezes the page; the fixes are chunking, Web Workers, and async APIs. The event loop is a runtime feature, and Node’s implementation has additional phases including setImmediate and process.nextTick.