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.
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.
Key Vocabulary
JavaScript is Single-Threaded
The Event Loop Model
The Golden Rule
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
How to Trace Async Code
Example 1: setTimeout
Example 2: Promise vs setTimeout
Tracing the Execution Order
Example 3: Nested Async
async/await Under the Hood
Common Mistakes
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?