JavaScriptRuntime

The JavaScript Event Loop

Watch the call stack, task queue, and microtask queue animate in real time.

By Forhad18 min readIntermediateInteractive Demo

How JavaScript Executes Code

JavaScript is single-threaded — it has one call stack and processes one thing at a time. But it can handle asynchronous operations through the event loop, which coordinates between three key structures:

The Three Players

  • Call Stack — where synchronous code runs frame by frame. Functions are pushed on when called and popped off when they return.
  • Microtask Queue — holds callbacks from Promise.then(), queueMicrotask(), and MutationObserver. Drained completely after each stack frame before any macrotasks.
  • Macrotask Queue — holds callbacks from setTimeout, setInterval, and I/O events. Processed one at a time, after all microtasks are drained.

The Golden Rule

After the call stack empties: drain all microtasks → pick one macrotask → repeat. This is why Promises always resolve before setTimeout, even with a 0ms delay.

Event Loop Simulator

Step through code execution and watch items move between the call stack, microtask queue, and macrotask queue.

Source Code
console.log("1: Start");

setTimeout(() => {
  console.log("4: setTimeout");
}, 0);

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

console.log("2: End");

Call Stack

console.log("1: Start")

Micro Queue

empty

Macro Queue

empty
Console Output
> 1: Start
Step 1 / 6