The event loop

Topic 1 of 5 in Asynchronous code6 min readBeginnerFree course

Overview

JavaScript runs your code on a single thread — it can only do one thing at a time. Yet pages stay responsive while waiting for timers and network requests. The event loop is how.

Understanding it explains questions that otherwise seem mysterious: why setTimeout(fn, 0) doesn’t run immediately, why a promise callback runs before a timer, and why a slow loop freezes the whole page.

The pieces

  • Call stack — the functions running right now. When a function is called it’s pushed on; when it returns it’s popped off.
  • Web APIs — the browser does the waiting (timers, network, events) outside your code.
  • Task queue — callbacks ready to run, such as timers and clicks.
  • Microtask queue — promise callbacks, which get priority.

The call stack runs one function at a time. Timers, fetch and click events are handed off to Web APIs, where the browser waits. When they finish, promise callbacks go to the microtask queue and timer, event and network callbacks go to the task queue. The event loop: when the stack is empty, run all microtasks, then one task, then repeat and repaint.

The event loop repeats one rule: when the call stack is empty, run all microtasks, then take the next task. Between tasks, the browser also gets a chance to update the screen.

Run to completion

Once a piece of JavaScript starts, nothing interrupts it. A click that happens while your code is running doesn’t jump in halfway — its handler waits in the task queue until your code finishes. This makes JavaScript much simpler than languages where threads can interrupt each other: within one function, nothing else can change your variables behind your back.

Seeing it in action

JavaScript
console.log('start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('end');
// start, end, promise, timeout

Step by step:

  1. console.log('start') runs immediately.
  2. setTimeout hands the callback to the browser’s timer and returns straight away. After 0 ms the callback joins the task queue.
  3. Promise.resolve().then(…) puts its callback in the microtask queue.
  4. console.log('end') runs. The script is finished; the call stack is empty.
  5. The event loop runs all microtasks: 'promise'.
  6. Then it takes the next task: 'timeout'.

Even with a delay of 0, the timer callback waits until the current code finishes and all promise callbacks have run. The delay is a minimum, not a guarantee.

Tasks versus microtasks

Tasks (macrotasks) Microtasks
setTimeout, setInterval callbacks .then, .catch, .finally callbacks
Events: clicks, key presses, load Code after await in an async function
Network and message callbacks queueMicrotask(fn)
One per loop turn All of them, before the next task

Because microtasks drain completely, a microtask that keeps adding more microtasks can starve the page just like an infinite loop.

How async code fits in

await pauses only the async function it’s in, not the whole program. The rest of the function is scheduled as a microtask once the awaited promise settles:

JavaScript
async function load() {
  console.log('1');
  await null;
  console.log('3'); // runs as a microtask
}

load();
console.log('2');
// 1, 2, 3

Why it matters

Long-running code blocks everything — including clicks and screen updates:

JavaScript
// Freezes the page for about 3 seconds
const stop = Date.now() + 3000;
while (Date.now() < stop) {}

During those three seconds, buttons don’t respond, animations stop and the browser may show a “page unresponsive” warning. The click handlers are queued, but the event loop can’t reach them until the loop ends.

Keep work in small pieces. Split heavy loops into chunks, or move them into a Web Worker, so the page can keep responding.

Splitting work into chunks

JavaScript
function processInChunks(items, handle, chunkSize = 500) {
  let i = 0;
  function nextChunk() {
    const end = Math.min(i + chunkSize, items.length);
    for (; i < end; i++) handle(items[i]);
    if (i < items.length) setTimeout(nextChunk, 0); // let the browser breathe
  }
  nextChunk();
}

Each chunk is a separate task, so clicks and repaints can happen in between.

Web Workers

For truly heavy calculations — image processing, parsing huge files — a Web Worker runs JavaScript on a separate thread. It can’t touch the page directly; it sends results back as messages, which arrive in your page’s task queue.

Node.js too

Node.js uses the same model, with its own APIs (files, network) doing the waiting. That’s why a single Node server can handle thousands of connections: it never sits idle waiting for one of them.

Exercise

Predict the order

Write down the order of the five logs before running the code.

JavaScript
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
queueMicrotask(() => console.log('D'));
console.log('E');

Summary

  • JavaScript runs on a single thread: one piece of code at a time, to completion.
  • The browser does the waiting (timers, network, events) outside your code.
  • Finished async work waits in a queue until the call stack is empty.
  • Promise callbacks (microtasks) run before timer and event callbacks (tasks).
  • Long-running code blocks clicks and screen updates — keep work in small pieces.