03

Browser & Runtime

Event Loop, microtasks, rendering pipeline

GoalUnderstand the Event Loop deeply enough to predict any async output order, explain UI freezes, and know where rendering fits.

Lessons

The Event Loop — four pieces

JavaScript is single-threaded — one Call Stack, one thing at a time. But the browser has other threads for networking, timers, and I/O. The Event Loop coordinates between them.

Four pieces: 1. Call Stack — where your JS runs. One frame per function call. 2. Web APIs — browser features (setTimeout, fetch, DOM events) that run on other threads. 3. Microtask Queue — high-priority callbacks: Promise.then, await continuations, queueMicrotask. 4. Macrotask Queue — lower priority: setTimeout, setInterval, DOM events.

The Loop's rule: > After each task (and after initial script), drain ALL microtasks before taking the next macrotask. Render may happen between macrotasks.

Predicting async output

js
console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => console.log(3));
console.log(4);
// Output: 1 4 3 2

Trace: 1. Sync runs: logs 1, schedules setTimeout (→ macrotask queue), schedules .then (→ microtask queue), logs 4. 2. Stack empty → drain microtasks: logs 3. 3. Take next macrotask: logs 2.

setTimeout(fn, 0) does NOT mean "run now". It means "queue in the macrotask queue after at least 0ms" — always behind all sync code and microtasks.

Blocking the main thread

The Event Loop only moves a callback when the Call Stack is empty. If synchronous code keeps the stack busy, nothing else can run — no callbacks, no paint, no user input.

js
button.onclick = () => {
  // 2-second synchronous loop — BLOCKS everything
  const start = Date.now();
  while (Date.now() - start < 2000) {}
  // UI is frozen for 2 seconds
};

This is the root cause of INP (Interaction to Next Paint) being terrible. Fix: Web Workers (offload to another thread) or chunking (break work into pieces, yielding between them with setTimeout).

Rendering Pipeline

The browser renders at ~60fps (every ~16.6ms). Rendering shares the main thread with JS.

JS → Style → Layout (Reflow) → Paint (Repaint) → Composite
  • Reflow — recalculate positions/sizes. Expensive. Triggered by width, height, position changes.
  • Repaint — fill in pixels. Triggered by color, background changes.
  • Composite — assemble layers. Cheap. transform and opacity animate here without reflow/repaint.
Animate with `transform`/`opacity` not `top`/`left`/`width` — the former goes straight to Composite, the latter triggers expensive Layout.

Challenges3

Write working code. Run to see output. Check to grade.

CH1
Predict the output order
Medium

Predict the EXACT output order of this code. Write five console.log calls in the correct order as your answer.

js
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve()
  .then(() => { console.log("C"); return 1; })
  .then(() => console.log("D"));
console.log("E");
JavaScript
CH2
async/await ordering
Medium

Predict the output order of this async/await code:

js
async function foo() {
  console.log(1);
  await Promise.resolve();
  console.log(2);
}
console.log(3);
foo();
console.log(4);
JavaScript
CH3
Boss: nested macro/micro
Boss

This is the hardest ordering puzzle. Trace it carefully and log the EXACT output sequence.

js
console.log("start");
setTimeout(() => console.log("timeout1"), 0);
Promise.resolve().then(() => {
  console.log("p1");
  setTimeout(() => console.log("timeout2"), 0);
});
Promise.resolve().then(() => console.log("p2"));
console.log("end");
JavaScript

References