2. Asynchronous JavaScript & Browser APIs
The Event Loop, Call Stack, Promises & Microtask Queue
Understand how single-threaded JavaScript handles async operations without freezing the browser: trace Call Stack, Web APIs, Microtasks (Promise.then), and Macrotasks (setTimeout).
- Trace execution order across the Call Stack, Microtask Queue, and Macrotask Queue
- Explain why Promise.then() callbacks always execute before setTimeout(..., 0)
- Create and chain Promises cleanly with .then(), .catch(), and .finally()
JavaScript runs on one single main thread—it can execute only one piece of code at a time. Yet browsers handle button clicks, smooth 60fps animations, timers, and 10 simultaneous fetch() calls without locking up. How?
The secret is the Event Loop and two priority queues: Microtasks and Macrotasks.
1. Interactive Event Loop Trace: Who Runs First?
Predict what this famous snippet logs before clicking through the stepper below:
console.log("1. Sync start");
setTimeout(() => console.log("4. Macrotask"), 0);
Promise.resolve().then(() => console.log("3. Microtask"));
console.log("2. Sync end");Call Stack
console.log('1. Sync start')
Microtasks (Priority!)
[]
Macrotasks (Timers)
[]
Step 1: Synchronous Call Stack runs first
JavaScript runs top-to-bottom on the Call Stack. '1. Sync start' logs immediately.
The Golden Rule of the Event Loop
- Synchronous code on the Call Stack runs completely from start to finish first (
1,2). - As soon as the Call Stack is empty, the Event Loop drains the ENTIRE Microtask Queue (
Promise.then,queueMicrotask,awaitcontinuations) (3). - Only when Microtasks are empty does the Event Loop pick one callback from the Macrotask Queue (
setTimeout, DOM click events) (4), then checks Microtasks again!
Because the Event Loop drains every microtask before moving to rendering or timers, a recursive Promise.resolve().then(loop) infinite chain will freeze the browser tab completely!
2. Promise States & Clean Chaining
A Promise is an object representing an eventual async value in one of three states:
pending— work is still in flight.fulfilled— succeeded with a result value (triggers.then()).rejected— failed with an Error (triggers.catch()).
Once a Promise settles (fulfilled or rejected), it is immutable—it can never change state again.
Try It Yourself in the Playground
Run this live Web Sandbox to observe the exact 1 → 2 → 3 → 4 execution order in real browser console logs (try adding another .then() to watch microtasks chain before setTimeout!):
Mini-Challenge: Write a delay(ms) helper returning new Promise((resolve) => setTimeout(resolve, ms)) and use .then() to log "Done waiting" after 200ms.
Quick Checkpoints
In what order do console.log('A'), setTimeout(() => console.log('B'), 0), and Promise.resolve().then(() => console.log('C')) execute?
Once a Promise transitions from pending to fulfilled, can it later reject?