Tutorials JavaScript Event Loop & Call Stack
Ch 63 / 78
Chapter 63 Advanced 9 min read JavaScript

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.

What you'll learn
How the JavaScript runtime environment is structured
What the Call Stack is and how frames are pushed/popped
How Web APIs hand off tasks outside the main thread
The difference between Microtask and Macrotask queues
Predicting the exact order of async output
Common gotchas — starvation, blocking, and stack overflow

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:

JS Engine (V8)
Executes your code. Contains the Call Stack (execution) and the Heap (memory allocation for objects).
Web APIs (Browser)
Provided by the browser: setTimeout, fetch, DOM events, XMLHttpRequest. These run outside the JS engine.
Microtask Queue
Holds callbacks from resolved Promises and queueMicrotask(). Processed before any macrotask.
Macrotask Queue
Holds callbacks from setTimeout, setInterval, I/O, and UI rendering events.
Event Loop
The coordinator — continuously checks if the Call Stack is empty, then picks the next task from the queues in priority order.
Heap
Unstructured region of memory where objects, arrays, and functions are stored. Managed by the garbage collector.

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.

JavaScript — Call Stack trace
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:

Call Stack
greet("K2infocom") ← top
sayHello()
anonymous (global)
Event Loop
Web APIs
setTimeout fetch DOM events
Microtask Queue
Promise.then queueMicrotask
Macrotask Queue
setTimeout cb setInterval cb
Stack Overflow
If a function calls itself recursively without a base case, the stack keeps growing until the engine throws a Maximum call stack size exceeded error — that's a stack overflow.

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.

JavaScript — setTimeout async handoff
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.

⚡
Free Resource
Download our JavaScript Cheat Sheet
Async patterns, event loop flow, promises — all on one page.
Get Sheet

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
JavaScript — Queue priority demo
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:

1
Execute all synchronous code on the Call Stack until it is empty. This is the current "task".
2
Drain the Microtask Queue completely. Every .then(), queueMicrotask(), and MutationObserver callback runs — including any new microtasks scheduled during this step.
3
Render (browser only): if the browser decides a repaint is due, it updates the screen here — between tasks, never in the middle of one.
4
Pick one Macrotask from the Macrotask Queue (e.g., a setTimeout callback), push it onto the Call Stack, and execute it.
5
Repeat from step 2 — flush all microtasks again, then handle the next macrotask. This loop runs indefinitely as long as there are tasks.
Key Insight
The Event Loop does not spin while the Call Stack is busy. It only checks for new tasks after the stack is empty. This is why a long-running synchronous function blocks everything — timers, clicks, renders — until it finishes.

Predicting Async Output Order

Can you guess the output of this code before running it? Work through it line by line:

JavaScript — Classic async order puzzle
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:

"1" — sync
"7" — sync
"3" — microtask
"5" — microtask
"4" — microtask
"2" — macrotask
"6" — macrotask
Why "5" before "4"?
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:

JavaScript — async/await execution order
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.

Advertisement

Common Pitfalls & Best Practices

Now that you understand the mechanism, here are the traps to avoid:

Blocking the Stack
Long synchronous loops (e.g., for with millions of iterations) freeze the UI. Break heavy work into chunks with setTimeout(fn, 0) or use a Web Worker.
Microtask Starvation
Infinitely chaining microtasks (.then → .then → ... in a loop) prevents macrotasks from ever running — timers and events are starved.
setTimeout ≠ exact timing
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.
Unhandled Promise Rejection
Rejected Promises without a .catch() silently fail in older environments. Always handle rejections or use try/catch with async/await.
JavaScript — Breaking up heavy work
// ❌ 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

Live Editor
✎ Editor
👁 Preview
Pro Tip
Open your browser's DevTools → Performance tab and record while you click "Run Demo". You'll see the exact call stack frames, task scheduler, and microtask checkpoints in a flame chart.
Quick Check — Chapter 63

Which of the following runs first after all synchronous code completes?

Chapter Summary
  • 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 await keyword 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel