Skip to main content

Welcome to a Grasp lesson

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

Lesson 18

Mastering Asynchronous Execution Order

Recommended resources

In our previous lesson, we established the foundational model of the JavaScript event loop, distinguishing between the macrotask and microtask queues and understanding their fundamental priority rule. You learned why Promise.then() executes before setTimeout(..., 0). Today, we're taking that model and pressure-testing it with the full complexity you'd face in a senior interview or a tricky production bug.

This lesson focuses squarely on mastering execution order prediction. We'll add two more players to our scenario: requestAnimationFrame and the queueMicrotask function. By the end, you will be able to look at a tangled mess of nested asynchronous calls and, with the precision of a debugger, state exactly what logs and when. This isn't just an academic exercise; it's the key to understanding why your UI might feel janky, why a state update appears "late," and how to orchestrate complex animations and data flows performantly.

Core Concepts: The Complete Execution Order

In the last lesson, our event loop cycle was: execute one macrotask, then drain the microtask queue. Now we must place rendering into this picture, which is where requestAnimationFrame (rAF) lives.

The updated, more precise event loop "tick" is as follows:

  1. Execute one Macrotask: A task from the macrotask queue is taken and run to completion. (The initial script execution counts as the first macrotask).
  2. Drain the Microtask Queue: After the macrotask completes, the engine executes all available microtasks until the queue is empty. This is a crucial, "run-to-completion" step for microtasks. If a microtask schedules another microtask, that new one is also executed in this same phase.
  3. Render Update (Optional): If needed, the browser may now update the UI. This involves a sequence of steps:
    • Running all requestAnimationFrame (rAF) callbacks.
    • Style calculation.
    • Layout (determining geometry and position of elements).
    • Paint (drawing the pixels to the screen).
  4. Go to Step 1: The loop repeats, looking for the next macrotask.

The most important rule for prediction is: Microtasks always run before requestAnimationFrame, and both always run before the next macrotask.

Let's see this in action with a typical interview puzzle. Before looking at the resources, try to predict the output of this code:

console.log('1. Sync');

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

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

requestAnimationFrame(() => {
  console.log('4. rAF');
});

queueMicrotask(() => {
  console.log('5. Microtask');
});

console.log('6. Sync');

The javascript.info article provides an excellent textual reference for the event loop algorithm, which you can use to verify your predictions.

Event loop: microtasks and macrotasks

This article from javascript.info clearly defines the two queues and provides a simplified but accurate algorithm for the event loop's operation.

Focus on two key parts. First, the section Macrotasks and Microtasks explains the strict priority of the microtask queue. Second, the Summary at the end provides a step-by-step algorithm that you should internalize.

The actual output of the code above is: 1, 6, 3, 5, 4, 2. Let's trace it:

  • Initial Macrotask (script execution):

    • console.log('1. Sync') runs.
    • setTimeout schedules its callback in the macrotask queue.
    • Promise.resolve().then() schedules its callback in the microtask queue.
    • requestAnimationFrame schedules its callback in the render steps queue.
    • queueMicrotask schedules its callback in the microtask queue.
    • console.log('6. Sync') runs.
    • The initial script ends. Call stack is empty.
  • Microtask Drain:

    • The event loop finds two items in the microtask queue: the promise callback (3) and the queueMicrotask callback (5).
    • It executes them in the order they were added. console.log('3. Promise') runs, then console.log('5. Microtask') runs.
    • The microtask queue is now empty.
  • Render Update:

    • The browser is now free to render. It runs the scheduled requestAnimationFrame callback. console.log('4. rAF') runs.
  • Next Macrotask:

    • The event loop checks the macrotask queue. It finds the setTimeout callback.
    • It moves it to the stack and runs it. console.log('2. Timeout') runs.

The Full Gauntlet: Nested and Chained Tasks

Predicting the order gets truly challenging when tasks start scheduling other tasks. This is where senior-level understanding is tested. What happens if a microtask schedules a setTimeout? Or a setTimeout schedules a Promise?

The video below walks through an excellent, complex example that mixes all these concepts, including chained promises. The key insight to watch for is how one microtask can add another microtask to the queue, and how the event loop must handle that before moving on.

Understanding the Event Loop Sequence of Tasks

Steve Griffith's video "Understanding the Event Loop Sequence of Tasks" provides a fantastic, practical demonstration of a complex sequence.

Watch from the code demonstration where a large block of mixed tasks is introduced. Follow along as the non-alphabetical output is revealed. Then, pay close attention to the explanation starting at the microtask explanation, which clarifies why chained promise .then() calls don't necessarily execute one after another if other microtasks were queued in between.

Let's analyze a common pattern from the video: a microtask scheduling another macrotask.

Promise.resolve().then(() => {
  console.log('Promise 1');
  setTimeout(() => {
    console.log('Timeout from Promise');
  }, 0);
});

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

Prediction: Promise 1, Timeout 1, Timeout from Promise.

Trace:

  1. Initial Script: The Promise.then callback is added to the microtask queue. The setTimeout callback is added to the macrotask queue.
  2. Microtask Drain: The Promise.then callback runs. It logs Promise 1. Crucially, it then calls setTimeout. This adds a new callback to the macrotask queue. The macrotask queue now contains ['Timeout 1', 'Timeout from Promise'].
  3. Next Macrotask: The event loop picks the first item from the macrotask queue: the Timeout 1 callback. It runs.
  4. Microtask Drain: The microtask queue is empty.
  5. Next Macrotask: The event loop picks the next item: the Timeout from Promise callback. It runs.

Here is the flowchart of a complete event loop iteration, which visually summarizes the process we've been discussing.

This flowchart shows the full cycle. Starting with a task, the engine checks for and executes all microtasks. Then, it may run rendering steps (including requestAnimationFrame), and finally, it selects the next macrotask to begin a new cycle.

Mental Model Update: The Restaurant Kitchen Manager

Let's update our kitchen analogy from the previous lesson to include requestAnimationFrame.

  • The Chef: The Call Stack (executes one thing at a time).
  • VIP Garnish Station: The Microtask Queue (Promise, queueMicrotask).
  • "Order Up!" Window: The Macrotask Queue (setTimeout, clicks).
  • The Kitchen Manager: The Event Loop.

The manager's process is now even more specific:

  1. Wait for the Chef to finish their current dish (current macrotask/script ends).
  2. Go to the VIP Garnish station and apply ALL garnishes until the station is completely clear (drain the entire microtask queue).
  3. Before sending the next dish order to the Chef, glance over at the expediter who is plating the food and tell them, "Wipe the rim of that plate before it goes out." (Run requestAnimationFrame callbacks). Only after this visual touch-up is the plate ready.
  4. Finally, go to the "Order Up!" window and give the Chef ONE new dish to cook (process one macrotask).
  5. Repeat.

The manager will never take a new order while there are still VIP garnishes to apply, and will always perform the final plate touch-up (rAF) after the garnishes but before the next full order.


Conclusion

You have now analyzed the complete, ordered flow of the JavaScript event loop, incorporating synchronous code, microtasks, rendering, and macrotasks. You can trace complex, nested scenarios and confidently predict their execution order.

Key Takeaways:

  • The strict order of operations in one event loop tick is: 1. One Macrotask -> 2. All Microtasks -> 3. Render Steps (including rAF) -> 4. Next Macrotask.
  • The microtask queue is fully drained in one go. A microtask can add another microtask, which will also be executed before the engine moves on to rendering or the next macrotask.
  • requestAnimationFrame is not a microtask or a macrotask. It's a distinct phase tied to the browser's rendering cycle, occurring after microtasks.
  • When a task (macro or micro) schedules another task, it is placed in the appropriate queue according to its type, and its execution will follow these priority rules.

In our next lesson, we will explore how async/await, which you use daily, is simply syntactic sugar built directly on top of the Promise and microtask queue mechanics we've just dissected. Understanding today's lesson is the key to truly understanding how async/await works under the hood.