Topic F1
The event loop
One thread, one stack, two queues: why A, D, C, B, and why pages freeze.
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.
- moving now
- passed / marked
- finished / the result
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, 3Why 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
setTimeout(f, 0) and Promise.resolve().then(g) are scheduled together. Which runs first?
Why don't clicks respond while a heavy loop runs?
The right way to let the browser paint in the middle of heavy work?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.