Learn JavaScript
❯ async.event_loop

The Event Loop (Micro & Macro Tasks) in JavaScript

$concept

The event loop processes work in strict priority: the call stack runs to empty, then ALL queued microtasks (promise reactions, queueMicrotask) drain, then ONE macrotask (timers, I/O, rendering) runs — repeating forever. Microtasks starve rendering if they chain endlessly; a resolved promise's .then always runs before any setTimeout, even a zero-delay one.

This ordering explains every async surprise: await yields to microtasks (not macrotasks), Promise.resolve().then(...) beats setTimeout(..., 0) always, and infinite microtask chains freeze pages exactly like blocking loops do.

$how it works
1

Stack first, always

Synchronous code runs to completion before any queued work — nothing preempts the running stack.

2

Microtasks drain fully

Promise reactions queue as microtasks and ALL run (including newly queued ones) before the next macrotask.

3

One macrotask per turn

Timers, I/O callbacks, and renders each take one loop turn — interleaved fairly, never starving each other.

4

Order is deterministic

Stack → microtasks → one macrotask → repeat — every async ordering puzzle resolves through this cycle.

$example
console.log("a");
setTimeout(() => console.log("b"), 0);
Promise.resolve().then(() => console.log("c"));
console.log("d");
Output
a
d
c
b
1a and d print synchronously — the stack runs uninterrupted first.
2Stack empty: the promise microtask (c) drains before any macrotask.
3Then one macrotask turn runs the timer (b) — deterministic micro-before-macro ordering.
$use cases
Predicting async execution order in every codebase
Choosing queueMicrotask for defer-without-timer-delay
Diagnosing starved rendering as microtask-chain overload
Understanding await suspension points precisely

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.