Asynchronous JavaScript

Event Loop

The Event Loop is the engine behind JavaScript's non-blocking async model. Understanding it explains why Promises resolve before setTimeout, how async/await works under the hood, and how to avoid freezing the UI.

What is the JavaScript event loop?

JavaScript runs on a single thread, and the event loop is how it handles asynchronous work without blocking. Synchronous code runs first on the call stack. When the stack is empty, the loop runs all queued microtasks (promise callbacks), then takes the next macrotask (timers, events, network callbacks). That's why Promise.resolve().then(…) runs before setTimeout(…, 0).

console.log("1");
setTimeout(() => console.log("4"), 0);      // macrotask
Promise.resolve().then(() => console.log("3"));   // microtask
console.log("2");
// prints 1, 2, 3, 4

Microtasks

Run after current task, before next macrotask. FIFO. All drain before render.

Promise .then() / .catch() / .finally()
await (continuation after awaited Promise)
queueMicrotask(fn)
MutationObserver callbacks
process.nextTick() [Node.js — runs even before Promise microtasks]

Macrotasks

One per event loop iteration. After each, all microtasks drain, then browser renders.

setTimeout(fn, ms) callbacks
setInterval(fn, ms) callbacks
I/O event callbacks (Node.js)
MessageChannel postMessage
Script execution (initial)
UI event callbacks (click, input…)

One Event Loop Iteration

  1. 1
    Execute one macrotask

    Pick the oldest task from the macrotask queue (e.g. a setTimeout callback) and run it to completion.

  2. 2
    Drain microtask queue

    Run ALL microtasks (Promises, queueMicrotask) until the queue is empty — including any newly queued during this step.

  3. 3
    Render (if needed)

    Browser checks if a visual update is needed and repaints. requestAnimationFrame callbacks fire here.

  4. 4
    Repeat

    Pick the next macrotask from the queue. If empty, the thread idles until a new task arrives.

Common Pitfalls

Long synchronous loops block the event loop — UI freezes, events queue up unprocessed
Break large tasks with await new Promise(r => setTimeout(r, 0)) every N iterations
Microtask starvation — queuing new microtasks in .then() forever prevents macrotasks from running
Ensure microtask chains are finite. Never create self-perpetuating Promise.resolve().then() loops.
Assuming setTimeout(fn, 0) fires immediately — it's deferred to the next macrotask at minimum
Use queueMicrotask() if you need to defer to after current sync code but before any macrotask
Expecting DOM mutations to be visible immediately after setting them in sync code
DOM mutations are batched. Use requestAnimationFrame or await a Promise to read back updated layout.

Interactive Event Loop Demo

Code Editor

<button id="run">Run</button>
<ol id="out"></ol>

Preview

Execution order — step by step

1 / 4
1

Synchronous code runs first

All sync statements execute top-to-bottom on the call stack. No async code runs during this phase — the stack must be empty first.

1 of 4
🔍Promise.resolve() vs setTimeout(fn, 0)
Promise.resolve().then(fn) schedules fn as a microtask — runs before the next macrotask. setTimeout(fn, 0) schedules fn as a macrotask — may run many microtask cycles later. For guaranteed-before-paint execution, always prefer microtasks via Promise or queueMicrotask().

🎯 Quick Check

In what order do these execute? (1) console.log('sync') (2) setTimeout(()=>console.log('macro'),0) (3) Promise.resolve().then(()=>console.log('micro'))

The Event Loop: summary

Key points

  • Long synchronous work blocks the whole page: no clicks, scrolling or rendering until it finishes.
  • The browser renders between macrotasks, so split heavy work into chunks or move it to a Web Worker.
  • setTimeout(fn, 0) means "as soon as possible after the current work", not "immediately".
  • queueMicrotask(fn) schedules a microtask directly.

Frequently asked questions

›Is JavaScript single-threaded?

Your JavaScript runs on one main thread, but the browser does networking, timers and rendering in parallel, and Web Workers give you extra threads.

›What is the difference between microtasks and macrotasks?

Microtasks (promise callbacks, queueMicrotask) all run right after the current code finishes. Macrotasks (timers, I/O, events) run one per loop turn, after the microtask queue is empty.