advertisement

JavaScript Event Loop Visualizer

Understand how JavaScript handles asynchronous operations with macro and micro tasks.

Call Stack

Track function execution

Macro Tasks

setTimeout, setInterval, I/O

Micro Tasks

Promises, queueMicrotask

Execution Order

See the exact sequence

Code Input

Event Loop Visualization

Call Stack

Micro Task Queue

Macro Task Queue

Console Output

Step 0 / 0

Current Step Explanation

Click "Visualize Execution" to see how JavaScript processes this code.

How the Event Loop Works

  1. Execute synchronous code on the call stack
  2. When stack is empty, check micro task queue
  3. Execute ALL micro tasks (Promises)
  4. Execute ONE macro task (setTimeout)
  5. Repeat from step 2

Key Concepts

  • Micro tasks: Promise.then, queueMicrotask
  • Macro tasks: setTimeout, setInterval, I/O
  • Micro tasks always run before macro tasks
  • Micro tasks can queue more micro tasks

Common Patterns

Expected Output Order

Classic Event Loop Question

console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');

// Output: 1, 4, 3, 2
Common Misconception

setTimeout(0) Runs Immediately?

Even with delay 0, setTimeout is a macro task and waits for the call stack AND micro tasks to clear.

// This will NOT print immediately
setTimeout(() => console.log('Not first!'), 0);
console.log('First!');
// Output: First!, Not first!

Frequently Asked Questions

Promises use the micro task queue, which always gets processed completely before the next macro task (like setTimeout). This ensures Promises resolve as quickly as possible.

The event loop will continue processing micro tasks until the queue is empty. This means recursive micro tasks can block macro tasks from running - be careful of infinite micro task loops!

requestAnimationFrame is neither - it runs as a separate "render" phase in the event loop, after micro tasks but scheduled to sync with the browser's display refresh rate (typically 60fps).