Frontend Case Studies

Topic F1

The event loop

One thread, one stack, two queues: why A, D, C, B, and why pages freeze.

10 min · intermediate

Watch: work runs one thing at a time. Watch the order the letters print in: things scheduled "as soon as possible" still wait their turn.

call stackmicrotasktaskoutput
  • moving now
  • passed / marked
  • finished / the result
Step 1 of 10

console.log('A'); setTimeout(() => log('B'), 0); Promise.resolve().then(() => log('C')); console.log('D'). In what order does it print?

JavaScript on a page runs on one thread. The event loop only picks up the next job when the call stack is empty.

Like a single cashier

One cashier serves one shopper to the end. Everyone else waits in line. There's also a priority line (microtasks): shoppers who only need to "finish paying" are served before the normal line. If one shopper has 300 items, everyone behind waits a long time, however important they are.

Code, for programmersPrint order
console.log("A");
setTimeout(() => console.log("B"), 0);   // task queue
Promise.resolve().then(() => console.log("C"));   // microtask queue
console.log("D");
// A, D, C, B

async function load() {
  console.log("1");
  await fetch("/api");    // everything after await becomes a microtask, later
  console.log("3");
}
load(); console.log("2");  // 1, 2, 3

Why a page feels frozen

The browser repaints about 60 times a second, but only between tasks. A function running for 500 ms means no new frame, no response to clicks and no animation for half a second. Google measures this as INP (Interaction to Next Paint); over 200 ms is rated as needing improvement.

Code, for programmersBreaking up heavy work
async function processAll(rows) {
  for (let i = 0; i < rows.length; i++) {
    process(rows[i]);
    if (i % 500 === 0) await new Promise((r) => setTimeout(r, 0)); // let clicks and paint in
  }
}

// or move it off the main thread entirely
const worker = new Worker(new URL("./filter.worker.js", import.meta.url));
worker.postMessage(rows);
worker.onmessage = (e) => render(e.data);

Quiz

  1. setTimeout(f, 0) and Promise.resolve().then(g) are scheduled together. Which runs first?

  2. Why don't clicks respond while a heavy loop runs?

  3. The right way to let the browser paint in the middle of heavy work?

0 of 3 answered.