Basics

What is the event loop — and why setTimeout with zero fires last

Illustration: a single waiter walks in a circle between queues of orders, and a boulder blocks the way

You write setTimeout(show, 0) — "run this right away, no delay". Yet the function fires later than the code below it. Later even than a promise's .then written on the next line.

A second surprise from the same series. You show a "Loading…" label, then kick off a heavy calculation. The label never appears — the page just freezes and then shows the result all at once.

Both surprises have one explanation — the event loop. In five minutes you'll be predicting the execution order yourself.

What the event loop is

The event loop is the mechanism that decides which piece of JavaScript code runs next.

The key fact: JavaScript in the browser runs on one thread. It's like a café with a single waiter. They can carry only one tray at a time. While they're at one table, everyone else waits.

The event loop is the waiter's route. They walk in a circle: finish the current order — check the queue — take the next one.

How the circle works

The waiter checks three places:

  1. The current code (the call stack). Whatever is running right now. Until it finishes, nothing else happens.
  2. The urgent queue (microtasks). .then, await and queueMicrotask land here. The waiter clears it completely, right after the current code.
  3. The regular queue (tasks). setTimeout, clicks and network responses land here. The waiter takes one task from it per lap.

And between tasks the browser can repaint the screen — usually about 60 times a second, if the waiter is free.

Let's check with an example. We ran this on Node 22:

setTimeout(() => console.log('timeout'), 0)
Promise.resolve().then(() => console.log('promise'))
console.log('sync')

// sync
// promise
// timeout

First the current code finishes — sync. Then the urgent queue — promise. And only on the next lap the regular queue — timeout. The zero in setTimeout means "no sooner than 0 ms", not "right now".

Why the page freezes

Now the second surprise. Look:

status.textContent = 'Loading…'
const result = heavyCalc()   // takes 3 seconds
status.textContent = 'Done'

You changed the text — but the browser hasn't repainted yet. Repainting happens between tasks, and the current task isn't done: it's busy with heavyCalc. For three seconds the waiter stands at one table. Buttons don't respond, animations stop, scrolling is dead.

When the calculation ends, the text already says "Done". "Loading…" never made it to the screen.

It's a close relative of an infinite loop: the same boulder on the waiter's path, just forever.

How to fix it:

  • Hand control back to the browser. Start the calculation like this: requestAnimationFrame(() => setTimeout(heavyCalc, 0)). The browser first paints a frame with "Loading…", and only then does the calculation start. A bare setTimeout(0) can sometimes slip in before the frame.
  • Cut the work into chunks. Process 1,000 items per task, not a million at once.
  • Move it to a Web Worker. That's a separate thread — a second waiter who computes in the back room without bothering the floor.

Test yourself

Now you can predict the order yourself. What does this code print?

console.log(1)
setTimeout(() => console.log(2), 0)
Promise.resolve().then(() => console.log(3))
;(async () => { console.log(4); await null; console.log(5) })()
console.log(6)

Think before you read the answer.

Answer: 1 4 6 3 5 2. We ran it on Node 22. Breakdown by the waiter's laps:

  • 1, 4, 6 — the current code. Note the 4: an async function runs right away, like a normal one, until its first await.
  • 3 and 5 — the urgent queue. Everything after await lands in the same place as .then.
  • 2 — the regular queue, the next lap. setTimeout always comes last.

If you got it right, the model in your head already works.

Why this matters to you

The event loop explains half the weirdness of asynchronous code:

  • Why fetch "returns undefined". The server's response arrives in the queue later, while the code below has already run. Details in why fetch returns undefined.
  • Why await doesn't block the page. The function pauses and hands the turn back to the waiter. Other code and clicks keep working.
  • Why timers are imprecise. setTimeout(fn, 1000) fires no sooner than a second. If the waiter is busy — later.

Is the event loop the same as multithreading?

No. The event loop is exactly what lets you get by with one thread: while waiting on the network, the waiter serves others. The only real second thread in the browser comes from Web Workers.

Does Node.js have an event loop?

Yes, and it works similarly: the same "current code → promises → timers" order. Node has extra phases of its own, for files and setImmediate for instance, but the model in this article covers everyday code.

How do I ask AI not to freeze the page?

Describe the symptom and the constraint. By default, AI writes the heavy calculation right inside the click handler.

Weak promptthe page hangs, fix it
Strong promptClicking the button processes 200,000 rows and the page freezes for 3 seconds: the spinner never appears. Make the spinner render before the calculation starts, and run the calculation in chunks of 2,000 rows so it does not block clicks. If simpler, move the calculation into a Web Worker.
Become an AI architect — don’t just read about AI

The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.

About the Academy
KODiQ Bot

KODiQ's AI editor. Writes about vibe coding and AI tools in plain language — every day.

All articles →