The JavaScript Event Loop, Explained with Examples

The JavaScript event loop is the coordinator that decides what code runs next. It connects the call stack, the task queues and the browser's rendering. It explains why a setTimeout with a zero-millisecond delay still runs after all of your synchronous code.

This article builds the picture one piece at a time. It starts with the call stack, then follows async work out to the Web APIs and back through the queues. By the end, you should be able to look at a short async snippet and predict the exact order its output prints in.

In short
  • JavaScript runs on one main thread. The event loop lets it handle slow work without freezing.
  • Synchronous code runs on the call stack first, from start to finish.
  • Timers and network requests wait outside the engine. Their callbacks come back through a queue.
  • All microtasks, such as promise callbacks, run before the next macrotask, such as a setTimeout.
  • A setTimeout delay is a minimum wait, not a guaranteed time.

Why does setTimeout(fn, 0) run last?

Almost every JavaScript developer hits this eventually. You call setTimeout with a delay of zero, expecting it to run right away. Yet its output appears after a loop that sits below it in the file. You asked for zero milliseconds, so why does it run last? The cause is that code which reads top to bottom doesn't always run top to bottom.

This confusion shows up in two ways. The first is mysterious ordering: console output comes out shuffled compared to the source. Reading the code top to bottom no longer works for debugging, so you end up guessing. The second is a frozen interface: one long function holds the thread, so clicks, typing and scrolling all wait. Once you understand the event loop, both problems make sense.

  • Mysterious ordering: logs appear in an order the source doesn't show
  • Frozen interfaces: one heavy task and clicks stop responding

What is the JavaScript event loop?

The event loop is the part of the runtime that decides what JavaScript runs next. A useful image is a traffic controller that never stops turning. In each turn of the loop, the call stack runs whatever code is on it. When the stack is empty, all waiting microtasks run. Then the browser gets a chance to render. Finally, one macrotask is taken from its queue, and the loop starts again.

Two ideas follow from this. Task queues are waiting rooms: a callback waits there until the call stack is empty, and it never cuts in while other code is running. Rendering happens in the gaps between turns, never in the middle of a function. The browser can't repaint while your function is still running. That is why a long-running function makes the page look frozen.

  • Call stack → Microtasks → Render → one Macrotask → repeat

Why does JavaScript need an event loop?

JavaScript runs your code on one main thread. That single thread still has to deal with timers, network responses and user input. Imagine JavaScript simply waited for slow work. A fetch would block the only thread, the page would freeze until the response arrived, and clicks and scrolling would stop working.

The event loop avoids this by handing slow work to the host, which is the browser or Node. The host watches the timers and sockets. JavaScript only reacts once something is ready. Meanwhile, the thread stays free for input, and the callback runs later. There is no second thread to take over while your code is busy, so waiting is never an option. This division of labor is the whole idea behind the loop.

How the call stack works

The first step is the call stack. Synchronous code runs here until the stack is completely empty. Think of a stack of plates: you always work on the top one. Say main() calls greet(). First main is pushed onto the stack. Then greet is pushed on top of it. When greet returns, it is popped off, leaving only main. When main finishes, it is popped too, and the stack is empty.

This step comes with two important guarantees. First, a function runs to completion: no timer or click can jump into the middle of it. Second, the event loop only checks its queues once the stack is empty. This is why your zero-delay timer always waits for every synchronous line to finish first.

  • Push main → main
  • Push greet → main, greet
  • Pop greet → main
  • Pop main → (empty, ready for queued callbacks)

Where does async work go? Web APIs and the task queue

The second step happens outside the stack. When your code calls setTimeout or fetch, the Web APIs take over. For a timer, the host counts down. For a fetch, it waits for the network response. These belong to the host, not to JavaScript itself, so your stack keeps running other code the whole time.

The subtle part comes when the work finishes. A finished timer's callback does not run right away. Instead, it is placed in the task queue and waits for an empty stack, just like the waiting rooms described above. Finishing only means the callback has joined the line. It runs when the loop reaches it.

Microtasks vs macrotasks: which runs first?

The third step adds a twist: there isn't just one queue. Microtasks include promise .then callbacks and queueMicrotask. Macrotasks include setTimeout, events and I/O. Microtasks run as soon as the stack empties. Macrotasks wait until every microtask has finished. In each turn, all microtasks run, but only one macrotask does. A microtask added during that process still runs in the same turn.

As a result, a resolved promise's callback always runs before a zero-millisecond setTimeout, because it sits in the higher-priority queue. There is a downside, though. If microtasks keep adding new microtasks, the loop never moves on. Timers and rendering can be starved, and the page stops updating.

  • Microtasks: Promise .then, queueMicrotask — all run every turn
  • Macrotasks: setTimeout, events, I/O — one runs per turn
  • Promise beats timer, every time
  • Endless microtasks can starve timers and rendering

Predict the output: a classic event loop example

Here is the classic interview question that puts all three steps together. The code logs A, schedules a zero-millisecond timeout that logs B, resolves a promise whose .then logs C, and finally logs D. The comment in the code already gives away the answer: A, D, C, B. Here is why.

First, the synchronous code prints A and then D, straight off the stack. Once the stack is empty, B is waiting in the task queue and C is waiting as a microtask. Microtasks go first, so C prints next. Then the loop takes the next macrotask and prints B. A zero delay only means the callback can run on a later turn of the loop. That answers the question from the start of this article.

  • Sync code → prints A, D
  • Stack empty → B waits in the task queue, C is a microtask
  • Microtasks → prints C
  • Next macrotask → prints B
  • Result: A D C B
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
# output: A D C B

Where the event loop shows up in real code

The event loop matters almost everywhere JavaScript runs. It drives UI response: keep the stack short and clicks feel instant. Fetch handling uses it to deliver responses through promises. A Node.js server uses it to serve many requests on one thread. Animation timing depends on frames getting their turn to render.

The details differ between the browser and Node, but the core model is the same: stack first, then microtasks, then the next task. A practical rule follows from it. When you have heavy work, split it into chunks spread across turns. That gives the loop room to render and handle input between them.

Common event loop mistakes to avoid

Two mistakes trip up even experienced developers, and both come from forgetting how the loop takes turns. The first is blocking the stack. In the example, a loop runs a billion empty iterations, and as the comment warns, it blocks every click and paint. While it runs, nothing else can. The fix is to break the work into chunks or move it to a worker.

The second mistake is assuming timer delays are exact. The example calls setTimeout with save and a delay of 100. As its comment notes, save runs after at least a hundred milliseconds, not exactly then. If the stack is busy, the callback waits longer. Don't rely on setTimeout for precise scheduling.

  • Blocking the stack freezes clicks, timers and rendering
  • A setTimeout delay is a minimum, not a guarantee
# blocks every click and paint
for (let i = 0; i < 1e9; i++) {}
# runs after AT LEAST 100 ms
setTimeout(save, 100);

Key takeaways

  • Synchronous code runs first on the call stack, from start to finish.
  • Web APIs do the waiting and queue finished callbacks instead of running them.
  • All microtasks run before the next macrotask.
  • Only one macrotask runs per turn of the loop.
  • Don't block the stack, and treat delays as minimums.
  • To predict any output, trace the stack, then microtasks, then the next macrotask.

Frequently asked questions

Why does setTimeout with 0 ms not run immediately?

A zero delay only makes the callback eligible on a later turn of the event loop. It has to wait for the call stack to empty and for all microtasks to finish. Only then can it run as the next macrotask.

Do promises run before setTimeout?

Yes. A resolved promise's .then callback is a microtask. Microtasks all run before the next macrotask, such as a setTimeout callback. That is why a resolved promise beats a 0 ms timeout every time.

What is the difference between microtasks and macrotasks?

Microtasks include promise callbacks and queueMicrotask. In each turn, all of them run as soon as the stack empties. Macrotasks include setTimeout, events and I/O, and only one runs per turn, after the microtasks are finished.

Is JavaScript single-threaded?

Your JavaScript runs on one main thread. Slow work like timers and network requests is handled by the host, meaning the browser or Node. JavaScript then reacts when the results come back through the event loop's queues.

Why does my page freeze during a long loop?

A function runs to completion on the call stack, and the browser can only render between turns of the loop. A long loop keeps the stack busy, so clicks, timers and painting all wait. Break the work into chunks or move it to a worker.

Does Node.js use the same event loop as the browser?

The details differ, but the core model is the same in both. Synchronous code on the stack runs first, then microtasks, then the next task. This is how a Node.js server can serve many requests on one thread.

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
Ad