The Event Loop
Call stack, task queue, microtasks, and how JavaScript schedules asynchronous work.
What you'll learn
- The single-threaded call stack and how frames push and pop
- Macrotasks (setTimeout, setInterval, I/O) and the task queue
- Microtasks (promise callbacks, queueMicrotask) and their priority
- Why microtasks run before the next macrotask
- How requestAnimationFrame fits into the rendering pipeline
Concept
Single Thread, One Stack
JavaScript runs on a single call stack — it executes one statement at a time. When a function is called, a frame is pushed onto the stack; when it returns, the frame pops. If a slow operation ran on this stack, the entire page would freeze. The event loop exists to keep the stack free by offloading slow work to the host environment (browser or Node) and running the callback later.
Macrotask Queue
When an async operation finishes (a timer fires, a network response arrives, a file read completes), its callback is placed in the macrotask queue (also called the task or callback queue). After the call stack is empty, the event loop takes one macrotask from the queue and runs it to completion. Then it checks for microtasks before taking the next macrotask.
Microtask Queue
Promise callbacks (.then, .catch, await continuations) and queueMicrotask() go into the microtask queue. Microtasks have higher priority: after every macrotask, the event loop drains the entire microtask queue before rendering or taking the next macrotask. This is why a resolved promise's then runs before a setTimeout(fn, 0) — the timer is a macrotask, the promise is a microtask.
The Ordering in Practice
This ordering has real consequences. A long chain of microtasks can starve the macrotask queue, delaying timers and I/O. Conversely, heavy macrotasks block rendering. Understanding the distinction explains many "why does this run first?" puzzles and is essential for writing correct async code.
requestAnimationFrame
For visual updates, requestAnimationFrame schedules a callback right before the browser repaints — typically ~60 times per second. It runs in a dedicated phase between microtask draining and rendering, making it the correct choice for animations. Using setTimeout for animations can cause jank because it is not synced with the display refresh.
Concurrency Without Threads
The event loop gives JavaScript concurrency (overlapping I/O) without parallelism (simultaneous execution). For true CPU parallelism, use Web Workers (browser) or worker_threads (Node). The event loop is about never blocking the single thread, not about running two things at the exact same instant.
Example
console.log("1. script start");
// Macrotask — setTimeout goes in the task queue
setTimeout(() => {
console.log("4. setTimeout (macrotask)");
}, 0);
// Microtask — promise.then runs before the next macrotask
Promise.resolve().then(() => {
console.log("3. promise (microtask)");
});
console.log("2. script end");
// Output order: 1, 2, 3, 4 — microtask beats macrotask
// Microtasks drain completely before the next macrotask
Promise.resolve()
.then(() => console.log("micro 1"))
.then(() => console.log("micro 2"))
.then(() => console.log("micro 3"));
setTimeout(() => console.log("macro after all micros"), 0);
// queueMicrotask — explicit microtask scheduling
queueMicrotask(() => console.log("queued microtask"));
// requestAnimationFrame — synced with rendering
let frame = 0;
function animate() {
console.log("frame", frame);
if (++frame < 3) requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
// A long microtask chain delays macrotasks (starvation)
async function starvationDemo() {
for (let i = 0; i < 3; i++) {
await Promise.resolve(); // microtask
console.log("await", i);
}
console.log("microtasks done");
}
starvationDemo();
Demonstrates the classic script→microtask→macrotask ordering, microtask queue draining, queueMicrotask, requestAnimationFrame for rendering, and how a chain of awaits (microtasks) runs before a setTimeout (macrotask).
Try it
- HTTP Request Tester
Network requests are macrotasks — observe how they interleave with promises.
- WebSocket Client Tester
WebSocket messages arrive as macrotasks — test the ordering with promise handlers.
Common mistakes
The mistake
Assuming setTimeout(fn, 0) runs immediately after the current code
The fix
setTimeout is a macrotask. Promise callbacks (microtasks) always run before the next macrotask. If you need to run code right after the current synchronous block, use queueMicrotask() or Promise.resolve().then().
The mistake
Creating an infinite microtask loop that starves the event loop
The fix
Because the microtask queue is fully drained before any macrotask, an endless chain of microtasks (e.g. recursive .then) prevents timers and I/O from running. Break long work into macrotasks with setTimeout to yield control.
Related Resources
Related Cheatsheets
- JavaScript Cheatsheet
Event loop, microtask vs macrotask, and scheduling reference.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.