Course contentsShow
← JavaScript
Lesson 1219 of 2,72327. The Event LoopFree lesson

Tracing Execution with a Diagram

Walking through a complex example step-by-step to predict execution order using the event loop model.

Tracing Execution with a Diagram

You'll learn how to manually walk through complex asynchronous code using the event loop model to predict the exact execution order before running any code.

The Skill of Mental Execution

Now that you understand the call stack, task queue, microtask queue, and event loop flow, you can trace code execution on paper (or mentally) by simulating what the JavaScript engine does. This means drawing out each step: what's on the stack, what's queued, and when each callback fires.

How to Trace Step-by-Step

  1. Start with the call stack: Mark synchronous code executing immediately
  2. Track async callbacks: Note when setTimeout schedules a task or .then() queues a microtask
  3. Empty the stack first: All synchronous code finishes before the event loop checks queues
  4. Process microtasks: Run all microtasks before moving to the next task
  5. Take one task: Execute the next task from the task queue, then repeat from step 3

Example Walkthrough

console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');

Trace:

  • Stack executes: 'A', schedules timeout task, queues microtask, 'D'
  • Stack empty → Check microtasks: run 'C'
  • Microtasks empty → Take task: run 'B'
  • Output: A, D, C, B

Drawing this visually—boxes for stack, queues with arrows showing movement—makes complex scenarios clear. You're essentially being the JavaScript engine.

Key Takeaway: Tracing execution with a diagram lets you predict async behavior by manually following the event loop rules: synchronous code first, then all microtasks, then one task at a time.