Hello! In our last lesson, we introduced the fundamental difference between synchronous and asynchronous code. We learned that while JavaScript can only do one thing at a time (it's single-threaded), it uses a system involving the Call Stack, Web APIs, a Task Queue, and an Event Loop to handle long-running tasks without freezing the application.
Today, we'll take a deep dive into that system, as you requested. We're going to pull back the curtain and see exactly how each part works. This is the "under the hood" knowledge that is crucial for understanding why your future code in frameworks like Next.js behaves the way it does, especially when fetching data.
Our learning outcome is to describe the roles of the call stack, web APIs, callback queue, and event loop in handling async operations. We'll also add a new, very important component to this model that is essential for modern JavaScript.
Let's start with a visual map of the territory we'll be exploring.

Part 1: The Cast of Characters
In the previous lesson, we met the main players. Now, let's formally define their roles. The classic talk "What the heck is the event loop anyway?" by Philip Roberts provides some of the clearest visualizations of this process.
What the heck is the event loop anyway? | Philip Roberts | JSConf EU
This video provides an excellent, animated walkthrough of the core components. As you watch, focus on the specific job of each part.
Watch the following segments: The Call Stack (04:08 - 07:18): Understand how it manages synchronous function calls in a Last-In, First-Out (LIFO) manner. Notice how a slow, synchronous function blocks the stack. The Solution (10:24 - 12:48): See how asynchronous callbacks and Web APIs are introduced as the solution to blocking. The Full Picture (12:48 - 14:55): This is the most important part. Watch carefully as it shows a setTimeout call being passed to a Web API, its callback going to the Callback Queue, and the Event Loop moving it back to the Call Stack only when the stack is empty.
Let's solidify those roles based on the video:
-
The Call Stack: This is part of the JavaScript engine. Its job is to execute code. When you call a function, it's pushed onto the stack. When the function finishes, it's popped off. It can only do one thing at a time. If a function on the stack takes a long time, everything else is blocked.
-
Web APIs: These are not part of the JavaScript engine; they are provided by the browser environment (or Node.js). When you call an asynchronous function like
setTimeoutor make a network request withfetch, the JS engine hands the operation off to the Web API. The Web API runs the task (e.g., the timer or the network request) in the background. -
The Callback Queue (or Task Queue): This is a simple queue that works on a First-In, First-Out (FIFO) basis. When a background task in the Web API is complete, its associated callback function is placed in this queue, waiting to be executed.
-
The Event Loop: This is the great orchestrator. It has one simple, continuous job: to check if the Call Stack is empty. If it is, the Event Loop takes the first task from the Callback Queue and pushes it onto the Call Stack, where it can finally be executed.
This system is why setTimeout(fn, 0) doesn't run immediately. The setTimeout call hands the callback to the Web API, the timer finishes instantly, and the callback is placed in the queue. However, it must wait there until all the synchronous code currently on the Call Stack has finished running.
Part 2: A New Player with Higher Priority — The Microtask Queue
The model we've just described works perfectly for things like timers and user events (like clicks). However, modern JavaScript introduced a new way to handle asynchronous operations called Promises. We'll learn all about Promises in the next lesson, but they are the foundation for data fetching in Next.js, so it's critical to understand how the runtime handles them.
Promise-related tasks are considered more urgent than setTimeout callbacks. To handle them, the runtime environment has a second, higher-priority queue.
- The Macrotask Queue: This is just another name for the Callback Queue we already know. It handles callbacks from
setTimeout,setInterval, and user events. - The Microtask Queue: This is a special, high-priority queue. It handles callbacks from Promises (
.then(),.catch(),.finally()) and other modern APIs.
The Event Loop's rule is actually a bit more nuanced:
- After a synchronous task on the Call Stack finishes, the Event Loop first checks the Microtask Queue.
- It will execute ALL tasks in the Microtask Queue until it's completely empty.
- Only when the Microtask Queue is empty will it take ONE task from the Macrotask Queue and push it to the Call Stack.
- After that one macrotask is done, it goes back to step 1 and checks the Microtask Queue again.
This ensures that Promise results are processed as quickly as possible, before less urgent tasks.
JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue
This distinction between microtasks and macrotasks is a key part of the modern event loop model. The video "JavaScript Visualized - Event Loop" by Lydia Hallie provides an excellent animation of this priority system.
Watch from 06:08 to 08:34. This section explains the Microtask Queue, its priority over the Task (Macrotask) Queue, and demonstrates how the Event Loop handles it. Pay close attention to how it ensures the microtask queue is entirely empty before moving to the task queue.
Part 3: Putting It All Together - A Battle of Queues
Let's see this in action. Consider the following code:
console.log('1: Sync');
setTimeout(() => {
console.log('2: Macrotask (setTimeout)');
}, 0);
Promise.resolve().then(() => {
console.log('3: Microtask (Promise)');
});
console.log('4: Sync');
What will the output order be? Let's trace it:
console.log('1: Sync')is pushed to the stack and runs immediately. Output:1: SyncsetTimeoutis pushed to the stack. It hands its callback() => console.log('2: ...')to the Web API and is popped off. The timer starts (for 0ms).Promise.resolve().then(...)is pushed to the stack. The promise resolves immediately, and its callback() => console.log('3: ...')is placed in the Microtask Queue. The call is popped off.console.log('4: Sync')is pushed to the stack and runs immediately. Output:4: Sync- The synchronous script is now finished. The Call Stack is empty.
- The Event Loop checks the Microtask Queue. It finds the Promise callback and pushes it to the stack. It runs. Output:
3: Microtask (Promise) - The Call Stack is empty again. The Event Loop checks the Microtask Queue. It's empty.
- The Event Loop now checks the Macrotask Queue. The
setTimeouttimer has finished, so its callback is in this queue. The Event Loop pushes it to the stack. It runs. Output:2: Macrotask (setTimeout)
The final output is:1: Sync4: Sync3: Microtask (Promise)2: Macrotask (setTimeout)
This animated GIF perfectly visualizes this exact priority system.

Test your understanding!
Predict the output of the following code snippet and explain the order.
console.log('Start');
setTimeout(() => {
console.log('Timeout 1');
Promise.resolve().then(() => console.log('Promise in Timeout'));
}, 0);
Promise.resolve().then(() => {
console.log('Promise 1');
setTimeout(() => console.log('Timeout in Promise'), 0);
});
console.log('End');
Show answer
The output will be:
Start
End
Promise 1
Timeout 1
Promise in Timeout
Timeout in Promise
Explanation:
StartandEndare logged synchronously.- The first
setTimeoutcallback (Timeout 1) is placed in the Macrotask Queue. - The first
Promisecallback (Promise 1) is placed in the Microtask Queue. - The main script finishes. The Event Loop runs.
- The Microtask Queue is checked first.
Promise 1is logged. Inside this callback, a newsetTimeout(Timeout in Promise) is scheduled, and its callback is added to the Macrotask Queue. - The Microtask Queue is now empty. The Event Loop processes one task from the Macrotask Queue:
Timeout 1is logged. Inside this callback, a newPromiseis scheduled (Promise in Timeout), and its callback is added to the Microtask Queue. - The Event Loop finishes the macrotask and immediately checks the Microtask Queue again before proceeding to the next macrotask. It finds
Promise in Timeoutand logs it. - Finally, with the Microtask Queue empty again, the Event Loop processes the last remaining item in the Macrotask Queue:
Timeout in Promiseis logged.
Conclusion and Textual Reinforcement
You've just completed a deep dive into one of JavaScript's most powerful and intricate features. Understanding this model is what separates a novice from an experienced developer.
To help you review and solidify these concepts, the article that accompanies the video on microtasks is an excellent resource.
JavaScript Visualized - Event Loop, Web APIs, (Micro)task ...
For a detailed textual summary with illustrations, please read the blog post "JavaScript Visualized - Event Loop, Web APIs, (Micro)task ...". It covers everything we've discussed today.
Read the article from the beginning down to the 'Recap' section. This will reinforce your understanding of the Call Stack, Web APIs, Task Queue, Event Loop, Microtask Queue, and the final summary.
Key Takeaways:
- The Call Stack executes synchronous code.
- Web APIs are background workers provided by the browser that handle async operations.
- The Macrotask Queue (or Callback Queue) holds low-priority tasks like
setTimeoutcallbacks. - The Microtask Queue holds high-priority tasks, primarily Promise callbacks.
- The Event Loop is the orchestrator with a clear set of priorities: it always empties the entire Microtask Queue before handling a single task from the Macrotask Queue.
Next Up
Now that you understand the mechanics of how JavaScript handles modern asynchronous operations, you are perfectly prepared for our next lesson. We will dive into the syntax and usage of Promises, the objects that use the Microtask Queue to manage asynchronous results in a clean and predictable way. This is the last major concept you need before we start fetching real data from APIs.