Quick Answer: Why Doesn't Asynchronous JavaScript Code Run in Written Order?

JavaScript is a single-threaded language, meaning it executes one instruction at a time on a single Call Stack without blocking the main thread on slow operations. Tasks are routed across three priority levels: synchronous code (Call Stack), high-priority microtasks (Microtask Queue — Promises, async/await), and standard callbacks (Macrotask Queue — setTimeout, UI events). Whenever the Call Stack clears, the Event Loop always drains the entire Microtask Queue before executing a single Macrotask—which is why a resolved Promise always runs ahead of setTimeout(..., 0).

When fetching data from an API, handling user clicks, or scheduling timers in a web application, seeing console logs appear out of top-to-bottom order is one of the most common surprises for web developers. Watching synchronous lines at the bottom of a file and Promise.then() callbacks execute before a setTimeout(..., 0) block is not random—it is the deterministic behavior of the JavaScript Event Loop. This guide explains the interaction between the Call Stack, Web APIs, Microtask Queue, and Macrotask Queue through concrete execution examples.

Table of Contents

Execution order in JavaScript is governed not by line numbers or zero-millisecond timers, but by the Event Loop rule that drains the entire Microtask Queue before picking up a single Macrotask.

1. Single-Threaded Execution and the Blocking Problem

Browser JavaScript runs on a single Call Stack primarily to protect DOM integrity—preventing race conditions where two threads attempt to mutate the same HTML element simultaneously. However, if network requests (fetch) or timers blocked that single thread synchronously, the browser tab would freeze completely during every network round-trip. To stay responsive, JavaScript offloads waiting operations to background Web APIs while continuing to execute synchronous instructions on the stack.

2. Event Loop Architecture: Call Stack, Web APIs, Microtasks, and Macrotasks

  • Call Stack: A LIFO (Last-In, First-Out) stack tracking currently executing synchronous functions.
  • Web APIs: Browser or runtime subsystems handling setTimeout timers, network I/O, and DOM events off the main thread.
  • Microtask Queue (High Priority): Holds Promise.then(), Promise.catch(), Promise.finally(), post-await continuations, and queueMicrotask() callbacks.
  • Macrotask / Callback Queue (Standard Priority): Holds setTimeout, setInterval, and user interaction event callbacks.
  [JAVASCRIPT EVENT LOOP PRIORITY CYCLE]

  ┌───────────────────────┐
  │   1. CALL STACK       │ ──> Executes all synchronous code until empty.
  └───────────┬───────────┘
              ▼ (Once Call Stack is empty)
  ┌───────────────────────┐
  │  2. MICROTASK QUEUE   │ ──> Drains ALL queued Promise.then / await tasks!
  └───────────┬───────────┘     (Includes newly spawned microtasks)
              ▼ (Once Microtask Queue is empty)
  ┌───────────────────────┐
  │  3. RENDER & PAINT    │ ──> Browser updates layout/pixels if a frame is due.
  └───────────┬───────────┘
              ▼
  ┌───────────────────────┐
  │  4. MACROTASK QUEUE   │ ──> Dequeues ONE setTimeout / UI event task,
  └───────────┬───────────┘     then loops back to Step 1.
              └──────────────────────────────────────────────────────────────▲

3. Step-by-Step Trace: Why setTimeout(0) Runs After a Promise

console.log("1. Sync Start");

setTimeout(() => {
  console.log("2. setTimeout (0 ms - Macrotask)");
}, 0);

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

console.log("4. Sync End");

Guaranteed console output order:

  1. Sync Start
  4. Sync End
  3. Promise.then (Microtask)
  2. setTimeout (0 ms - Macrotask)
  1. 1. Sync Start runs immediately on the Call Stack.
  2. setTimeout(..., 0) registers with Web APIs and queues its callback into the Macrotask Queue.
  3. Promise.resolve().then(...) queues its callback into the Microtask Queue.
  4. 4. Sync End runs synchronously, leaving the Call Stack empty.
  5. The Event Loop checks the Microtask Queue first and executes 3. Promise.then.
  6. Only after the Microtask Queue is completely empty does the Event Loop dequeue 2. setTimeout from the Macrotask Queue.

4. Synchronous, Microtask, and Macrotask Comparison Table

Task Category JavaScript Constructs Execution Priority Per-Cycle Processing Rule
Synchronous Code Standard functions, loops, variable assignments, new Promise(...) executor body 1st (Highest) Runs uninterrupted until the Call Stack is completely empty.
Microtasks Promise.then/catch/finally, code after await, queueMicrotask, MutationObserver 2nd (Immediately after Call Stack) Drains all queued microtasks before moving on.
Macrotasks setTimeout, setInterval, I/O callbacks, UI click/keyboard events 3rd (Lowest) Processes only one task per Event Loop turn.

5. How async / await Executes Under the Hood

async function fetchData() {
  console.log("A: Sync start inside async function");
  await Promise.resolve();
  console.log("B: After await (queued as a Microtask)");
}

console.log("C: Global start");
fetchData();
console.log("D: Global end");

// Output Order: C -> A -> D -> B

Everything inside an async function before the first await executes synchronously (A). Upon hitting await, the function suspends, schedules everything below await (B) into the Microtask Queue, and returns control to the caller so D finishes first.

6. UI Freezing and Microtask Starvation Pitfalls

  • Microtask Starvation: Because the Event Loop will not render frames or handle user clicks until the Microtask Queue is empty, recursively scheduling new Promises inside a .then() handler freezes the browser tab indefinitely.
  • CPU-Bound Call Stack Blocking: Heavy synchronous loops block user interaction. Offload heavy data parsing to Web Workers or chunk work across Macrotask turns.
Frontend Performance Tip: Use requestAnimationFrame for Visual Updates

Instead of driving animations with setTimeout(..., 16), use requestAnimationFrame() so visual updates synchronize directly with the browser's display refresh and paint cycle.

7. Frequently Asked Questions (FAQ)

1. Why doesn't setTimeout(fn, 0) execute immediately after 0 milliseconds?

The 0 ms delay specifies the minimum waiting time before the callback enters the Macrotask Queue—not immediate execution. It must wait for the Call Stack and the entire Microtask Queue to clear first, and nested timers are clamped to a minimum 4 ms delay per the HTML specification.

2. Does using async/await make JavaScript multi-threaded?

No. Your JavaScript code still executes on a single main thread. While I/O and timers wait in background runtime layers, callbacks always execute sequentially on the main Call Stack unless you explicitly spawn Web Workers.

3. If two Promises resolve at the same time, which runs first?

Their .then() handlers are queued into the Microtask Queue in FIFO (First-In, First-Out) order and execute in the exact order they were attached.

4. How can I guarantee order when making multiple network fetch calls?

Network response times vary, so parallel requests may resolve out of order. Use sequential await calls if requests depend on each other, or pass them to Promise.all([req1, req2]) to run concurrently while preserving array result order.

5. Is the Node.js Event Loop identical to the browser Event Loop?

The core priority rule (Sync → Microtask → Macrotask) is consistent, though Node.js implements multi-phase I/O polling via libuv and gives process.nextTick() even higher priority than standard Promise microtasks.