Part 01 · How the Browser Works

The Event Loop: Tasks and Microtasks

Main threadTask queueMicrotasksPromises

One main thread runs your JavaScript, styles, layout and input handling. How tasks, microtasks and rendering take turns, and why a long task freezes the page.

⏱ 6 min · Station 5 of 125

The problem

A customer taps "Add to cart". Nothing happens. They tap again. A third of a second later the button finally says "Added!", and the cart has two of the item. The handler recalculates prices, taxes and delivery for the whole cart, synchronously, in 300 ms.

Nothing is slow on the server. The page was simply busy: there's one thread that runs your JavaScript, handles clicks, and draws frames, and while it was running the handler it could do nothing else.

The idea

The browser runs a page's JavaScript, style, layout, paint and input handling on one main thread. The event loop decides what that thread does next:

  • A task (a script, a timer, a click handler, a network callback) runs from start to finish. Nothing interrupts it.
  • When the task ends, all microtasks run (promise callbacks, code after await, queueMicrotask), including any new ones they add.
  • Then, if a frame is due, the browser renders: requestAnimationFrame callbacks, style, layout, paint.
  • Then the next task.

A task that runs for 50 ms or more is a long task. During it, clicks wait and frames don't happen.

How it works

  1. Pick one task from a task queue. Timers, user input, network events and postMessage each go to a queue; the browser can prefer input over timers, but it only ever runs one task at a time.
  2. Run it to completion. Your click handler can't be paused halfway for another click. A while loop that takes 300 ms takes 300 ms of the main thread, period.
  3. Drain the microtask queue. Every .then callback and every resumed async function runs now, before any timer or click. A microtask that queues another microtask keeps the loop here: an endless chain of microtasks freezes the page just like an endless loop.
  4. Maybe render. About every 16.7 ms (at 60 Hz) the loop gets a rendering opportunity: run requestAnimationFrame callbacks, then style, layout, paint and hand the frame to the compositor. If the page is busy, the opportunity is missed.
  5. Repeat.

What the user feels for a click is: input delay (waiting for the current task to finish) + processing (your handlers) + presentation delay (until the next frame shows the result). The sum is what the Core Web Vital INP (Interaction to Next Paint) measures (Part 7).

Predict first

A script calls setTimeout(cb, 0), requestAnimationFrame(cb), Promise.resolve().then(cb) and queueMicrotask(cb), in that order. Which callback runs first after the script ends?

Visual

call stackmain thread: one thing at a timemicrotask queuepromise.then, awaittask queuesetTimeout, clicks, fetch donerender steprAF, style, layout, paintscriptsetTimeout cbthen cbawait restthen cbawait restsetTimeout cbrAF -> paintthe script runs to the end: nothing can interrupt itstack empty: ALL microtasks run before anything elsethen ONE task from the task queuewhen a frame is due: rAF callbacks, then style, layout, painta long task here means no frame and no click handling until it ends
The script runs on the call stack and queues a timer (task queue) and two promise callbacks (microtask queue). When the stack empties, all microtasks run, then one task, then the render step.

Ways to schedule work

APIQueueRunsUse it for
plain codecurrent tasknow, to completionshort work
promise.then, await, queueMicrotaskmicrotaskright after the current task, before anything elsecontinuing async logic
setTimeout(fn, 0)taskafter microtasks and (often) a frame; clamped to 4 ms+ when nestedyielding to let input and rendering in
requestAnimationFramerendering steponce before the next paintvisual updates, animation
scheduler.yield() / postTasktask (prioritised)soon, with input allowed in betweenbreaking up long tasks (Chromium; check support)
requestIdleCallbackidlewhen the thread has nothing to dolow-priority work (analytics, prefetch)
Web Workerother threadin parallelheavy CPU work (Part 7)

See it live

Measured on an Intel i3-10110U laptop (4 threads), 7 GB RAM, Ubuntu 26.04, Chrome 151 headless via Playwright 1.64.1, no throttling, the lab in Docker on the same machine.

loop.html logs the order its callbacks run in, and has an "Add to cart" button whose handler blocks for 300 ms. It also asks the browser for its own record of slow interactions (the Event Timing API) and long tasks:

<!doctype html>
<html>
<head><title>event loop</title></head>
<body>
  <button id="buy">Add to cart</button>
  <p id="msg"></p>
  <script>
    // 1. Who runs first? Every callback writes to the log in the order it actually ran.
    const log = [];
    window.order = log;
    log.push("1 script: start");
    setTimeout(() => log.push("timeout 0 ms"), 0);
    requestAnimationFrame(() => log.push("requestAnimationFrame"));
    Promise.resolve().then(() => log.push("promise.then"));
    queueMicrotask(() => log.push("queueMicrotask"));
    (async () => {
      log.push("2 async fn: before await");
      await null;
      log.push("async fn: after await");
    })();
    log.push("3 script: end");

    // 2. A click handler that blocks the main thread for 300 ms (think: a heavy cart recalculation).
    document.getElementById("buy").addEventListener("click", () => {
      const t = performance.now();
      while (performance.now() - t < 300) {}
      document.getElementById("msg").textContent = "Added!";
    });

    // The browser's own record of slow interactions and long tasks.
    window.events = [];
    new PerformanceObserver((l) => {
      for (const e of l.getEntries())
        if (e.name === "click" || e.name === "pointerdown")
          window.events.push({
            name: e.name,
            inputDelay: e.processingStart - e.startTime,
            processing: e.processingEnd - e.processingStart,
            presentation: e.startTime + e.duration - e.processingEnd,
            duration: e.duration,
          });
    }).observe({ type: "event", durationThreshold: 16, buffered: true });
    window.longtasks = [];
    new PerformanceObserver((l) => {
      for (const e of l.getEntries()) window.longtasks.push(Math.round(e.duration));
    }).observe({ type: "longtask", buffered: true });
  </script>
</body>
</html>

tools/loop.mjs reads the log, clicks the button once, then clicks twice 50 ms apart:

// node loop.mjs: the event loop in two experiments on loop.html.
import { open, WEB, ms } from "./lib.mjs";

const { browser, page } = await open();
await page.goto(`${WEB}/x/loop.html`, { waitUntil: "load" });
await page.waitForTimeout(200);

// 1. In what order did the callbacks run?
console.log("1) order the callbacks actually ran in:");
(await page.evaluate(() => window.order)).forEach((l, i) => console.log(`   ${i + 1}. ${l}`));

// 2. Click "Add to cart": its handler blocks the main thread for 300 ms.
await page.click("#buy");
await page.waitForTimeout(600);
const e = await page.evaluate(() => ({ events: window.events, longtasks: window.longtasks }));
console.log("\n2) click on 'Add to cart' (handler busy for 300 ms):");
for (const x of e.events)
  console.log(`   ${x.name.padEnd(12)} input delay ${ms(x.inputDelay).padStart(6)}   handler ${ms(x.processing).padStart(6)}   until next paint ${ms(x.presentation).padStart(6)}   total ${ms(x.duration).padStart(6)}`);
console.log(`   long tasks seen: ${e.longtasks.map((d) => d + " ms").join(", ")}`);

// 3. Two quick clicks: the second one arrives while the first handler is still running.
await page.evaluate(() => (window.events.length = 0));
const box = await page.locator("#buy").boundingBox();
const [x, y] = [box.x + 10, box.y + 10];
await Promise.all([page.mouse.click(x, y), page.waitForTimeout(50).then(() => page.mouse.click(x, y))]);
await page.waitForTimeout(900);
const e2 = await page.evaluate(() => window.events);
console.log("\n3) two clicks 50 ms apart:");
for (const x of e2.filter((x) => x.name === "click"))
  console.log(`   click        input delay ${ms(x.inputDelay).padStart(6)}   handler ${ms(x.processing).padStart(6)}   total ${ms(x.duration).padStart(6)}`);
await browser.close();
1) order the callbacks actually ran in:
   1. 1 script: start
   2. 2 async fn: before await
   3. 3 script: end
   4. promise.then
   5. queueMicrotask
   6. async fn: after await
   7. timeout 0 ms
   8. requestAnimationFrame

2) click on 'Add to cart' (handler busy for 300 ms):
   pointerdown  input delay   2 ms   handler   0 ms   until next paint 302 ms   total 304 ms
   click        input delay   3 ms   handler 300 ms   until next paint   1 ms   total 304 ms
   long tasks seen: 303 ms

3) two clicks 50 ms apart:
   click        input delay   1 ms   handler 300 ms   total 600 ms
   click        input delay 251 ms   handler 300 ms   total 552 ms

Reading it:

  • Part 1. The script runs to its end first (lines 1-3), including the synchronous part of the async function. Then the three microtasks, in the order they were queued. Then the timer, and finally requestAnimationFrame, at the next frame.
  • Part 2. The click's handler took 300 ms (processing). The pointerdown event before it was cheap (0 ms), but it had to wait 302 ms for the next paint, because the click handler ran before any frame could be drawn. The browser also reported one long task of 303 ms. From the user's side: 304 ms from tap to visible response.
  • Part 3. The second click arrived 50 ms after the first one, while the first handler still had 250 ms to go. It waited 251 ms before its handler even started (input delay), then ran 300 ms: 552 ms in total. The first click's frame was also pushed back to 600 ms, because the browser ran the waiting click before painting.
Input delayHandlerTotal until paint
one click3 ms300 ms304 ms
2nd click, 50 ms later251 ms300 ms552 ms

Google's guidance for a "good" INP is 200 ms or less. One 300 ms handler already fails it, and a second tap makes it worse.

In real apps

  • Update the button first, compute later. Show "Adding..." in the handler, then await a yield (scheduler.yield(), or setTimeout(0) where it's not available) before the heavy work, so the browser can paint in between.
  • Chunk big loops. Filtering 10k products or rebuilding a big list in 5-10 ms slices with a yield between them keeps every frame and every click within budget. React's concurrent rendering does this for rendering work (Part 2).
  • Move CPU work to a Web Worker. Search indexes, price calculations and image processing run off the main thread (Part 7).
  • Watch long tasks in production. The same longtask and event observers you saw above feed RUM tools (Part 13).

What goes wrong in production

  • Double submits. The user taps twice during a long task, both clicks are queued, both run: two orders, two items in the cart. Disable the button immediately or make the action idempotent.
  • Microtask loops. A recursive promise chain or a MutationObserver that triggers itself never lets the loop reach rendering: the page freezes with no long-task warning that's easy to read.
  • "setTimeout(fn, 0) runs immediately" - it doesn't. It runs after microtasks, maybe after a frame, and nested timers are clamped to at least 4 ms.
  • Third-party scripts (chat widgets, analytics) adding long tasks right when the page becomes interactive, so the first tap feels dead.

Key takeaway

One main thread: one task at a time, then all microtasks, then maybe a frame. Anything that runs long delays every click and every frame behind it, so keep tasks short and yield to the browser between chunks of work.

Practice

Change the click handler in loop.html so it first sets the message to "Adding...", then yields with await new Promise((r) => setTimeout(r, 0)), then does the 300 ms of work and sets "Added!". Predict the new processing time and the time until the next paint for the click. Run node loop.mjs to check.

Answer

The handler now ends right after setting "Adding..." and scheduling the timer, so processing drops to about 0 ms, and the browser gets a rendering opportunity before the timer task runs. The click's next paint (showing "Adding...") comes within a frame instead of after 304 ms. In our run the click didn't even appear in the Event Timing list, which only records interactions of 16 ms or more (the durationThreshold in loop.html). The 300 ms of work still happened, as a separate long task (longtasks: 300), and anything clicked during it still waits. Yielding makes the response visible fast; to make the work itself not block, split it into smaller chunks or move it to a worker.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →