The Event Loop and the Call Stack

Intermediate · 13 min

How a single-threaded engine runs timers and other work without blocking — the call stack, the host environment, and why microtasks cut ahead of macrotasks.

Before thisClosures

Lydia Hallie · 13 min

The Event Loop and the Call Stack

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Lydia HallieReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • JavaScript runs on a single call stack: one thread, one frame executing at a time. Nothing about the language itself lets two pieces of your code run simultaneously.
  • `setTimeout`, network requests, and file reads aren't run by the JavaScript engine at all — the engine hands them off to the host environment (the browser or Node), which does the actual waiting and only hands a callback back once the work is done.
  • There are two queues for callbacks waiting to run: the macrotask queue (timers, I/O, UI events) and the microtask queue (promise callbacks, `queueMicrotask`) — and they are not treated equally.
  • The event loop's rule is: once the call stack is empty, drain the *entire* microtask queue before running even one macrotask. Microtasks can queue more microtasks, and all of those run too, before the loop ever looks at the macrotask queue again.
  • This is exactly why a `Promise`'s `.then()` callback logs before a `setTimeout(fn, 0)` callback, even though both were "scheduled" at the same moment: one goes into the microtask queue, the other into the macrotask queue, and microtasks always go first.

The puzzle: one thread, but things still happen “at once”

JavaScript gives you exactly one call stack. One thread, one thing running at a time — there’s no built-in way for two functions to execute simultaneously the way they might across two CPU cores. And yet a web page can run an animation, wait on a network request, and respond to a click, all without any of them visibly blocking the others. If the engine really can only do one thing at a time, how does any of that work?

The short answer: the JavaScript engine isn’t the one doing the waiting. Things like setTimeout, fetch, and reading a file aren’t JavaScript features in the sense that the engine executes them line by line the way it executes your functions. They’re handed off to the host environment — the browser or Node — which has its own machinery for timers and networking, running entirely outside the call stack. The engine starts the request, immediately moves on to the next line of your code, and only comes back to the result once the host environment says it’s ready. That hand-off, and the bookkeeping that brings the result back, is the event loop.

The call stack: one thing at a time, strictly

The call stack is simple: calling a function pushes a frame onto it, returning pops that frame off. It’s last-in-first-out, like a stack of plates — whatever function is currently running is always the one at the top, and it has to finish (or itself call something, which goes on top of it) before control returns to whatever called it. As long as there’s anything on the stack, the engine is busy, and nothing else — no queued callback, no timer, no promise handler — gets a turn.

That “nothing else runs while the stack is busy” rule is the whole reason a long, synchronous loop freezes a page: the stack never empties, so the event loop never gets a chance to hand it anything new to do.

Two queues, and they are not equal

Once something handed off to the host environment finishes — a timer fires, a response arrives — its callback doesn’t jump onto the call stack directly. It gets placed in a queue, waiting for the stack to be empty. There are two such queues, and the distinction between them is the crux of this lesson:

  • The macrotask queue holds setTimeout/setInterval callbacks, I/O completions, and UI events.
  • The microtask queue holds Promise callbacks (.then, .catch, .finally) and anything scheduled with queueMicrotask.

The event loop’s rule, every single time the call stack becomes empty, is: drain the entire microtask queue — including any new microtasks that got added while you were draining it — and only once it’s completely empty, take one task from the macrotask queue. Then repeat. Microtasks always get priority, and they get to fully exhaust themselves before a macrotask gets a turn.

Why promises “jump the line”

This is the part that trips people up the first time they see it:

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
// logs: A, D, C, B

setTimeout’s callback is a macrotask, no matter how small its delay. Promise.resolve().then()’s callback is a microtask. Both get scheduled during the same synchronous pass through the script, but the synchronous code (A, D) runs first, and then — because the microtask queue is drained before any macrotask is even considered — C logs before B, even though the setTimeout was written earlier in the code and asked for the shortest possible delay. A 0ms timeout was never a promise of immediacy; it just means “whenever the event loop next reaches a macrotask,” and a microtask always gets there first.

The embedded video walks through exactly this mechanism with the browser’s Web APIs, the call stack, and both queues drawn out step by step — watching a setTimeout and a .then() race against each other visually is the fastest way to make this ordering stick.

Where this fits

This lesson leans on closures: every callback handed to setTimeout or a promise is a function that closed over variables from its surrounding scope, and that’s exactly what lets it still do something useful once the event loop finally gets around to running it, possibly long after the code that scheduled it has finished. From here, the rest of this group is really one long answer to the same question — how do you write code against something that hasn’t happened yet — starting with the oldest answer, callbacks, and ending at the async/await syntax built on top of promises.

Check yourself

  1. 01If JavaScript only has one call stack, how can a `fetch()` request run "in the background" while the rest of your script keeps executing?

    It isn't actually the JavaScript engine running it in the background — the engine hands the request off to the host environment (the browser's networking layer, or Node's), which does the waiting outside of JavaScript entirely. The engine's call stack is free to keep running other code in the meantime, and the host environment only queues a callback once the response is ready.

  2. 02What's the difference between the macrotask queue and the microtask queue, and which one does the event loop prefer?

    Macrotasks are things like `setTimeout` callbacks, I/O completions, and UI events; microtasks are promise callbacks (`.then`/`.catch`/`.finally`) and `queueMicrotask`. The event loop always prefers microtasks: whenever the call stack empties, it runs every microtask currently queued — including new ones added while draining the queue — before it touches the next macrotask.

  3. 03What does this code log, and why: `console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');`?

    It logs `A`, `D`, `C`, `B`. `A` and `D` run immediately as synchronous code. The `setTimeout` callback goes into the macrotask queue and the `.then()` callback goes into the microtask queue; once the synchronous code finishes and the stack is empty, the event loop drains the microtask queue first (`C`), and only then takes the next macrotask (`B`) — regardless of the `0`ms delay.

  4. 04Does a `setTimeout(fn, 0)` run `fn` immediately, the instant the timer is scheduled?

    No. Even with a delay of `0`, the callback still has to wait for the current synchronous code to finish, for the entire microtask queue to drain, and for the macrotask queue to actually reach it. `0`ms is a minimum delay, not a guarantee of immediacy — it just means "as soon as the event loop would otherwise get to a macrotask," which is almost never instantly.

  5. 05What happens if a microtask callback keeps scheduling more microtasks, forever?

    The event loop can get stuck: its rule is to fully drain the microtask queue before moving on to even one macrotask, so a microtask that keeps adding more microtasks never lets the loop reach the macrotask queue at all. In a browser this can block rendering and any pending timers indefinitely — it's a real, if uncommon, way to freeze a page.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark