JavaScript Tutorial: The Event Loop
How JavaScript actually runs — the call stack, event loop, microtask queue, macrotask queue, and why setTimeout(fn, 0) isn't instant.
The engine behind async
Understanding the event loop is what separates developers who can reason about async JavaScript from those who are constantly confused by ordering surprises.
It explains why `setTimeout(fn, 0)` doesn't run immediately, why Promise callbacks run before setTimeout callbacks, and why `await` pauses the function but not the whole program.
What you'll learn in this JavaScript the event loop tutorial
This interactive JavaScript tutorial has 8 hands-on exercises. Estimated time: 22 minutes.
- Synchronous code — the call stack — JavaScript executes code on a **call stack** — last in, first out (LIFO).
- setTimeout — the macrotask queue — When `setTimeout(fn, 0)` is called:
- Promises — the microtask queue — Promise callbacks run in the **microtask queue** — which is checked BEFORE the macrotask queue.
- Microtasks run before next macrotask — The microtask queue is completely drained between every macrotask.
- The event loop and await — `await` is syntactic sugar for `.then()`. Under the hood:
- queueMicrotask — low-level scheduling — `queueMicrotask(fn)` adds a function directly to the microtask queue — without a Promise wrapper.
- Blocking the event loop — Since JavaScript is single-threaded, CPU-intensive synchronous code blocks everything — including timers, incoming HTTP …
- Build a task scheduler — Final challenge — no starter code.
JavaScript The Event Loop concepts covered
- The engine behind async