Event Loop & Call Stack
JavaScript is single-threaded — yet it handles timers, network requests, and user events without freezing the page. The secret? The Event Loop. Understanding how the Call Stack, Web APIs, Microtask Queue, and Macrotask Queue work together is the key to writing predictable async code.
The JavaScript Runtime Environment
When people say "JavaScript is single-threaded", they mean the JS engine (like V8 in Chrome/Node.js) has one Call Stack — only one piece of code executes at a time. But the browser (or Node.js) provides extra components that work alongside the engine:
setTimeout, fetch,
DOM events, XMLHttpRequest. These run
outside the JS engine.
queueMicrotask(). Processed before any macrotask.
setTimeout, setInterval, I/O, and UI rendering events.The Call Stack
The Call Stack is a LIFO (Last In, First Out) data structure that tracks which function is currently executing. Every time a function is called, a new execution context (stack frame) is pushed on top. When the function returns, its frame is popped off.
function greet(name) {
return "Hello, " + name;
}
function sayHello() {
const msg = greet("K2infocom"); // greet() pushed onto stack
console.log(msg); // after greet() returns, log runs
}
sayHello(); // sayHello() pushed first
// Stack order (bottom → top):
// [anonymous] ← global
// [sayHello]
// [greet] ← currently running
Here's a visual snapshot of the stack as greet() is executing:
Web APIs — Offloading Async Work
When you call setTimeout(fn, 1000), the
JS engine doesn't wait 1 second itself. It hands the timer off to the browser's Web API
layer, which runs it in a separate (non-JS) thread. After 1 second, the Web API
places the callback into the Macrotask Queue.
console.log("1 — Start");
setTimeout(() => {
console.log("3 — Timer callback (macrotask)");
}, 0); // 0ms delay — still async!
console.log("2 — End");
// Output:
// 1 — Start
// 2 — End
// 3 — Timer callback (macrotask)
Even with a 0 ms delay, setTimeout always fires after the current synchronous
code finishes — because its callback sits in the Macrotask Queue waiting for the stack to be
empty.
Microtask vs Macrotask Queue
This is where most developers get tripped up. There are two task queues, and they are processed in a strict priority order:
| Property | Microtask Queue | Macrotask Queue |
|---|---|---|
| Priority | 🔺 Higher — runs first | Lower — runs after microtasks |
| Sources | Promise .then/.catch/.finally, queueMicrotask(), MutationObserver |
setTimeout, setInterval, setImmediate (Node), I/O, UI events |
| Draining | All microtasks are flushed before the next macrotask begins | One macrotask is run per event loop tick |
| Risk | Infinite microtask loop starves macrotasks (page freezes) | Heavy macrotasks block UI rendering |
console.log("A — sync");
setTimeout(() => console.log("D — macrotask (setTimeout)"), 0);
Promise.resolve().then(() => console.log("C — microtask (Promise)"));
console.log("B — sync");
// Output order:
// A — sync
// B — sync
// C — microtask (Promise) ← before setTimeout!
// D — macrotask (setTimeout)
The Promise callback (C) fires before the setTimeout callback (D) even though both were queued at roughly the same time — because microtasks always drain first.
The Event Loop — Step by Step
The Event Loop runs a continuous cycle called a "tick". Here's exactly what happens each tick:
.then(), queueMicrotask(), and MutationObserver
callback runs — including any new microtasks scheduled during this step.
setTimeout callback), push it onto the Call Stack, and execute it.
Predicting Async Output Order
Can you guess the output of this code before running it? Work through it line by line:
console.log("1"); // sync
setTimeout(() => console.log("2"), 0); // macrotask
Promise.resolve()
.then(() => console.log("3")) // microtask 1
.then(() => console.log("4")); // microtask 2
queueMicrotask(() => console.log("5")); // microtask 3
setTimeout(() => console.log("6"), 0); // macrotask
console.log("7"); // sync
The output, in order:
queueMicrotask("5") is scheduled before .then("4") because the second .then is only queued after the first .then("3") resolves. When "3" runs, it queues "4" — but "5"
was already in the microtask queue. So: 3 → 5 → 4.
async/await Under the Hood
async/await is syntactic sugar over
Promises — every await suspends the function and schedules
the rest as a microtask:
async function fetchData() {
console.log("B — inside async fn (before await)");
await Promise.resolve(); // suspends here — schedules rest as microtask
console.log("D — resumed after await (microtask)");
}
console.log("A — sync");
fetchData();
console.log("C — sync, after fetchData() call");
// Output:
// A — sync
// B — inside async fn (before await)
// C — sync, after fetchData() call
// D — resumed after await (microtask)
An async function runs synchronously until
it hits the first await, then yields control
back to the caller. Everything after await behaves like a
.then() callback — a microtask.
Common Pitfalls & Best Practices
Now that you understand the mechanism, here are the traps to avoid:
for with millions of iterations) freeze the UI. Break
heavy work into chunks with setTimeout(fn, 0) or use
a Web Worker..then → .then → ... in a loop) prevents macrotasks
from ever running — timers and events are starved.setTimeout(fn, 100) means
"at least 100ms", not exactly. If the stack is busy, the callback waits longer. Never
rely on timers for precise timing..catch() silently fail in older environments. Always
handle rejections or use try/catch with async/await.
// ❌ BAD — blocks the thread for ~2s
function heavyWork() {
for (let i = 0; i < 1_000_000_000; i++) { /* ... */ }
}
// ✅ GOOD — yields to event loop every chunk
function chunkedWork(items, chunkSize = 1000) {
let index = 0;
function processChunk() {
const end = Math.min(index + chunkSize, items.length);
while (index < end) { /* process items[index] */ index++; }
if (index < items.length) {
setTimeout(processChunk, 0); // yield — let UI breathe
}
}
processChunk();
}
Try It Yourself
Which of the following runs first after all synchronous code completes?
- JavaScript is single-threaded — one Call Stack, one thing runs at a time.
- The Call Stack is LIFO: functions are pushed when called, popped when they return.
- Web APIs (setTimeout, fetch, DOM events) run outside the JS engine and place callbacks into queues when done.
- The Microtask Queue (Promises, queueMicrotask) has higher priority and is fully drained before any macrotask runs.
- The Macrotask Queue (setTimeout, setInterval, I/O) runs one task per event loop tick.
- An
awaitkeyword suspends an async function and schedules its continuation as a microtask. - Never block the Call Stack with long synchronous work — use chunking or Web Workers instead.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.