01 / 21

Async Execution &
The Event Loop

Understand how JavaScript handles asynchronous operations with a single thread: the call stack, task queues, and the event loop that keeps everything running smoothly.

JavaScript

Why Does Async Matter?

JavaScript runs on a single thread: it can only do one thing at a time. Without asynchronous execution, every network request, timer, or file read would freeze the entire page until it completes.

Synchronous
Each line waits for the previous one to finish. Slow tasks block everything.
Asynchronous
Long tasks run in the background. The main thread stays free and responsive.

Key Vocabulary

Call Stack
A LIFO structure tracking which function is currently executing.
Web APIs
Browser-provided features (timers, fetch, DOM events) that run outside the stack.
Task Queue
A FIFO queue where completed async callbacks wait to be pushed onto the stack.
Event Loop
The mechanism that checks: "Is the call stack empty? If yes, move the next task onto it."

JavaScript is Single-Threaded

SINGLE THREAD (Call Stack) Task A Task B Slow Task C Task D... Blocks everything after it! WITH ASYNC: Offload slow work Task A Task B Task D C callback

The Event Loop Model

Call Stack main() greet() (empty slots) Web APIs setTimeout(cb, 1000) fetch('/api/data') addEventListener() offload Task Queue (Callback Queue) cb1 cb2 ... done! Event Loop push "Is the stack empty?"

The Golden Rule

1
Execute synchronous code on the call stack, top to bottom.
2
Offload async tasks (timers, network, events) to Web APIs.
3
When a task completes, its callback enters the task queue.
4
Event loop checks: stack empty? Move next callback from queue to stack.

Microtasks vs Macrotasks

Not all async callbacks are equal. The event loop processes two types of queues, and one always takes priority.

Microtask Queue Macrotask Queue
Priority Higher: runs first Lower: runs after
Sources Promise .then/.catch, queueMicrotask setTimeout, setInterval, I/O, UI events
Draining All microtasks drain before any macrotask One macrotask per loop iteration
Risk Infinite microtasks can starve macrotasks Long tasks can delay rendering

Callbacks vs Promises

Callbacks
A function passed as an argument, called when the async task finishes. Simple but leads to "callback hell" with deep nesting.
Promises
An object representing a future value. Chains with .then() and .catch(). Flatter code, better error handling, uses the microtask queue.

How to Trace Async Code

1
Run all synchronous code first. Go line by line through the script as if async doesn't exist yet.
2
When you hit an async call (setTimeout, fetch, Promise), note it: it's been offloaded to the Web API.
3
After all sync code completes, drain the microtask queue: all .then() and await continuations run next.
4
Then process one macrotask (e.g., setTimeout callback). Repeat from step 3.
5
Keep cycling until both queues are empty and the stack is clear.

Example 1: setTimeout

1console.log("A"); 2 3setTimeout(function() { 4 console.log("B"); 5}, 0); 6 7console.log("C");

Example 2: Promise vs setTimeout

1console.log("1"); 2 3setTimeout(() => console.log("2"), 0); 4 5Promise.resolve().then(() => console.log("3")); 6 7console.log("4");

Tracing the Execution Order

Execution Timeline Phase 1: Synchronous log("1"), register setTimeout, register Promise.then, log("4") → 1, 4 Phase 2: Microtask Promise .then() → 3 Phase 3: Macro setTimeout cb → 2 Final Output: 1, 4, 3, 2 sync → microtask → macrotask event loop checks

Example 3: Nested Async

1setTimeout(() => { 2 console.log("timeout"); 3 Promise.resolve().then(() => 4 console.log("inner promise") 5 ); 6}, 0); 7 8Promise.resolve().then(() => 9 console.log("outer promise") 10); 11 12console.log("sync");

async/await Under the Hood

async function fetchData() { console.log("start"); // sync const data = await fetch("/api"); // pauses here console.log("done"); // microtask } fetchData(); console.log("after call"); // sync

Common Mistakes

✕ setTimeout(0) = instant
A 0ms timer still goes through the macrotask queue: it runs after all sync code and microtasks, never immediately.
✕ await blocks the thread
await only pauses that function. The main thread stays free. Other code and events continue to execute.
✕ Promises are macrotasks
Promise callbacks (.then, .catch) use the microtask queue, which has higher priority than setTimeout's macrotask queue.

Summary at a Glance

Concept What It Does Queue Type
Call Stack Tracks current execution N/A (immediate)
setTimeout / setInterval Delays a callback Macrotask
Promise .then() Runs after promise resolves Microtask
async/await Pauses function, resumes later Microtask
Event Loop Moves tasks to stack when empty Orchestrator
Web APIs Handle async work in background Feeds both queues

Question 1 of 5

What is the output of the following code?
console.log("A"); setTimeout(() => console.log("B"), 0); console.log("C");

Question 2 of 5

Which queue do Promise .then() callbacks enter?

Question 3 of 5

What does the event loop do?

Question 4 of 5

Given this code, what is the output?
console.log("1"); Promise.resolve().then(() => console.log("2")); setTimeout(() => console.log("3"), 0); console.log("4");

Question 5 of 5

When you use await inside an async function, what happens to code after the await line?