Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 17

Understanding the JavaScript Event Loop

Recommended resources

Welcome to the first lesson of Module 3. In the previous module, we explored execution context and closures, focusing on how JavaScript functions remember their surrounding state. Now, we shift our focus to an equally critical question: when does your code actually run? This brings us to the heart of JavaScript's concurrency model: the event loop.

This lesson is foundational. You'll trace the complete journey of a piece of code from the call stack, through browser APIs, into one of two critical queues—the macrotask and microtask queues—and finally back to the stack for execution. We'll also pinpoint exactly when the browser gets a chance to render updates. Mastering this cycle is a non-negotiable step toward senior-level competency, as it underpins nearly every advanced asynchronous pattern and performance optimization in the language.

Why This Matters at a Senior Level

[Always asked]

Mid-level engineers know that async/await works. Senior engineers know why it works and can debug the subtle, infuriating timing bugs that arise when it doesn't behave as expected. The event loop is the master scheduler of the JavaScript universe. Without a precise mental model of it, you're flying blind when dealing with issues like unresponsive UIs, out-of-order state updates, or performance bottlenecks. Interviewers test this relentlessly because it's the dividing line between someone who just uses async patterns and someone who can build and debug robust, high-performance systems with them. Being able to explain why a Promise.then() fires before a setTimeout(..., 0) isn't just trivia; it's a litmus test for deep platform understanding.


Core Concepts: The Rules of Concurrency

Let's start with a classic interview puzzle. Before reading ahead, predict the order in which the following code logs to the console:

console.log('A: Sync Start');

setTimeout(() => {
  console.log('B: Timeout');
}, 0);

Promise.resolve().then(() => {
  console.log('C: Promise');
});

console.log('D: Sync End');

Many developers would guess A, D, B, C, assuming the setTimeout with a zero delay runs first. The actual output is A, D, C, B.

Why? The answer lies in the components of the JavaScript runtime and the specific rules they follow. Let's build this model from the ground up.

1. The Core Components: More Than Just the V8 Engine

JavaScript is single-threaded, meaning it has only one call stack and can only execute one piece of code at a time. This is simple and predictable, but it creates a problem: what happens when a task is slow? The entire application freezes.

To solve this, the JavaScript runtime environment (like a browser) provides more than just the engine. The legendary JSConf talk by Philip Roberts provides the best visual introduction to these concepts.

What the heck is the event loop anyway? | Philip Roberts | JSConf EU

This talk, "What the heck is the event loop anyway?", is a rite of passage for JavaScript developers. It visualizes the key components and their interactions.

Watch these key segments to build a foundational mental model: The full picture: See the distinction between the JS Runtime (V8) and the additional Web APIs, event loop, and callback queue provided by the browser. The Call Stack: Understand how synchronous code is executed. The problem of blocking: See a visual demonstration of why slow synchronous code freezes the browser UI. The solution: This is the most critical part. Watch how setTimeout uses a Web API, a callback queue (task queue), and the event loop to execute asynchronously without blocking.

From the video, you now have the main pieces:

  1. Call Stack: Executes synchronous code.
  2. Web APIs: Handles asynchronous tasks like setTimeout or fetch in the background.
  3. Task Queue (or Macrotask Queue): A waiting list for callbacks from Web APIs.
  4. Event Loop: Its one job is to check if the call stack is empty. If it is, it moves the first item from the task queue onto the call stack to be run.

This explains why setTimeout doesn't run immediately, but it doesn't explain our original puzzle. Why did the Promise run before the timeout? Because there's one more piece to the puzzle.

2. The Full Picture: Macrotasks vs. Microtasks

The "task queue" we just discussed is more accurately called the macrotask queue. There is a second, higher-priority queue called the microtask queue.

  • Macrotasks: These include callbacks from setTimeout, setInterval, I/O operations, and user interaction events (like clicks). The event loop processes one macrotask per "tick".
  • Microtasks: These include callbacks from Promise.then/catch/finally and queueMicrotask. The event loop processes the entire microtask queue after each macrotask, before it does anything else.

This distinction is the key to solving almost any "what does this log?" interview question.

The following article provides a fantastic, detailed diagram and explanation of this complete system.

Event Loop - 33 JavaScript Concepts

This article breaks down the full JavaScript runtime environment and clarifies the priority of microtasks.

First, study the diagram in the section The JS Runtime Environment. Pay close attention to the two separate queues and the direction of the arrows. Next, read the section Tasks vs Microtasks. This clearly lists what creates each type of task and presents a simplified algorithm for the event loop. The critical rule is in step 2: "Process ALL microtasks (until queue is empty)".

Here is a visual summary of the process:

This diagram illustrates the complete event loop cycle. Events like user input and timers add tasks to the Macrotask queue. Promises and DOM mutations add tasks to the Microtask queue. The event loop first processes a macrotask, then completely drains the microtask queue, and finally checks if a render is needed before starting the next cycle.

3. Tracing The Full Cycle

Now we can define one full "tick" of the event loop with precision:

  1. Execute Synchronous Code: Run the current task on the call stack until it is empty. This is the initial script execution.
  2. Drain the Microtask Queue: After the stack is empty, check the microtask queue. Execute all queued microtasks, one by one, until the queue is empty. If a microtask adds another microtask, that new one is also executed in this same step.
  3. Update Rendering (if needed): The browser now has a chance to perform UI updates. It will recalculate styles, perform layout, and paint the screen. Callbacks from requestAnimationFrame are executed right before this step.
  4. Process One Macrotask: Take the oldest task from the macrotask queue, push its callback onto the call stack, and execute it.
  5. Repeat: Go back to Step 2.

Let's trace our original puzzle using these rules:

console.log('A: Sync Start'); // Step 1

setTimeout(() => { // Step 1: Web API creates a timer. Callback goes to macrotask queue later.
  console.log('B: Timeout');
}, 0);

Promise.resolve().then(() => { // Step 1: Callback is immediately added to the microtask queue.
  console.log('C: Promise');
});

console.log('D: Sync End'); // Step 1
  1. Initial Script (Macrotask):

    • console.log('A: Sync Start') runs. Output: A: Sync Start.
    • setTimeout is called. The browser's timer API gets the callback.
    • Promise.resolve().then() is called. The promise resolves immediately, so its .then() callback is placed in the microtask queue.
    • console.log('D: Sync End') runs. Output: D: Sync End.
    • The initial script finishes. The call stack is now empty.
  2. Drain Microtasks:

    • The event loop checks the microtask queue. It finds the promise callback.
    • It moves the promise callback to the stack and runs it. console.log('C: Promise') executes. Output: C: Promise.
    • The microtask queue is now empty.
  3. Render (if needed):

    • The browser could now repaint the screen.
  4. Process Macrotask:

    • The event loop checks the macrotask queue. By now, the 0ms timer from setTimeout has completed and its callback is waiting.
    • It moves the setTimeout callback to the stack and runs it. console.log('B: Timeout') executes. Output: B: Timeout.

Final Output: A: Sync Start, D: Sync End, C: Promise, B: Timeout.

This precise, predictable order is the foundation of modern asynchronous JavaScript.

JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue

To solidify this, let's walk through a more complex example. Lydia Hallie's video includes an excellent interactive quiz that mixes different async APIs.

Watch the section from this quiz and try to predict the output yourself. Then, follow her step-by-step explanation to see how the queues are processed.


Mental Model: The Restaurant Kitchen

A great way to remember these components and their priorities is with an analogy.

  • The Call Stack is the single Chef: The chef can only cook one dish at a time. Whatever they are working on, they must finish it completely ("run-to-completion").
  • Web APIs are the kitchen's Ovens and Timers: You can tell the oven to cook something for 20 minutes (setTimeout) or to start a long sous-vide process (fetch). These run in the background without occupying the chef.
  • The Macrotask Queue is the "Order Up!" window: When an oven timer dings, the finished dish is placed here. These are regular orders.
  • The Microtask Queue is the "VIP Garnish" station: These are urgent, last-minute additions to an order that must be done right now. For example, adding fresh parsley just before a plate goes out.
  • The Event Loop is the Kitchen Manager: The manager's process is strict:
    1. Wait for the Chef to finish their current dish (call stack to be empty).
    2. Immediately go to the VIP Garnish station and handle ALL requests there (drain the microtask queue).
    3. Glance at the dining room to see if a table needs bussing (update rendering).
    4. Go to the "Order Up!" window and give the Chef ONE new dish to cook (process one macrotask).
    5. Repeat.

The kitchen manager will never give the chef a new regular order if there are still VIP garnishes to be applied.


Conclusion

You have now traced the full event loop cycle, the engine that drives JavaScript's non-blocking concurrency. You can distinguish between the different execution contexts and predict how they will be scheduled.

Key Takeaways:

  • JavaScript is single-threaded, with one call stack. Asynchronous behavior is handled by the surrounding runtime environment (e.g., the browser).
  • There are two primary queues: the high-priority microtask queue (for Promises, queueMicrotask) and the standard macrotask queue (for setTimeout, I/O, UI events).
  • One "tick" of the event loop consists of: draining the entire microtask queue, checking for rendering updates, and then processing one task from the macrotask queue.
  • This predictable scheduling allows for fine-grained control over execution order, enabling urgent updates (microtasks) to happen before less critical ones (macrotasks) and before the next screen paint.

In our next lesson, we will put this model to the test. We'll move beyond simple examples and into complex, nested scenarios involving setTimeout, Promise.then, queueMicrotask, and requestAnimationFrame to ensure you can confidently predict execution order in any situation you might face in an interview or in production code.