Back to all articles
JavaScriptEvent LoopAsync

JavaScript Event Loop Explained — A Complete Visual Guide

Code Visualizer Team•March 10, 2026•5 min read
Understand how the JavaScript event loop works with interactive visualizations. Learn about the call stack, microtask queue, macrotask queue, and why Promise.then runs before setTimeout.

JavaScript Event Loop Explained — A Complete Visual Guide

The JavaScript event loop is one of the most important concepts every JS developer must understand. It's the mechanism that allows JavaScript — a single-threaded language — to handle asynchronous operations like network requests, timers, and user interactions without blocking the main thread.

What Is the Event Loop?


The event loop is a continuous process that checks whether the call stack is empty. When it is, it looks at the task queues (microtask and macrotask) and pushes the next callback onto the stack for execution.

This is what makes setTimeout, Promise.then, and async/await work — they schedule callbacks onto these queues instead of blocking the main thread.

The Call Stack


JavaScript has a single call stack, which means it can only execute one piece of code at a time. When a function is called, it's pushed onto the stack. When it returns, it's popped off. If the stack is too deep (infinite recursion), you get the famous "Maximum call stack size exceeded" error.

Microtasks vs Macrotasks


Not all async callbacks are created equal. JavaScript has two task queues:
  • Microtask queue: Promise.then, queueMicrotask, MutationObserver

  • Macrotask queue: setTimeout, setInterval, setImmediate, I/O
  • The crucial rule: all microtasks are processed before the next macrotask. This is why Promise.then always executes before setTimeout, even if the timer is set to 0ms.

    Classic Interview Question


    console.log("Start");
    setTimeout(() => console.log("Timeout"), 0);
    Promise.resolve().then(() => console.log("Promise"));
    console.log("End");

    Output: Start → End → Promise → Timeout. The Promise callback (microtask) runs before the setTimeout callback (macrotask), even though both were scheduled before the call stack was empty.

    Try It Yourself


    Paste this code into Code Visualizer's JavaScript Playground and watch the event loop process each task in real-time.

    Async/Await and the Event Loop


    async/await is syntactic sugar over Promises. When you await a value, the code after the await is scheduled as a microtask. The function pauses and the event loop continues processing other tasks.

    Conclusion


    The event loop is JavaScript's superpower and its biggest source of confusion. By visualizing each step — call stack, microtask queue, macrotask queue — you can build an intuitive mental model that makes async code predictable.

    Try This Interactively

    See the event loop in action with interactive step-by-step playback in our JavaScript visualizer.

    Try Event Loop Playground