Starvation and Blocking
Two different ways to freeze a page: occupy the stack, or keep the microtask queue permanently full.
Blocking means a long synchronous frame the event loop cannot interrupt. Starvation means microtasks that queue more microtasks, so the loop never reaches rendering or timers. Both look identical to a user and have different fixes.
EXERCISE
1Blocking: Holding the Stack
Any long synchronous operation stops everything, because the event loop only runs between frames, never inside one.
The rule from lesson 1 has a cost. A callback runs only when the stack is empty, so anything that keeps the stack busy stops every timer, every click, and every frame of rendering.
What blocking looks like:
function blockFor(ms) {
const end = Date.now() + ms;
while (Date.now() < end) {
// spinning
}
}
document.querySelector("button").addEventListener("click", () => {
console.log("clicked");
});
blockFor(3000);
console.log("done");
// For three seconds: clicks do nothing visible, animations stop,
// the page does not repaint. The click events are queued, not lost,
// and all of them fire at once after "done".
The common real causes are rarely a deliberate spin loop:
// A large synchronous parse
const data = JSON.parse(veryLargeString);
// A sort over a very large array
const sorted = millionItems.sort((a, b) => a.value - b.value);
// A loop doing layout reads inside it
for (const el of manyElements) {
total += el.offsetHeight; // forces the browser to recompute layout
}
None of these look dangerous. All of them are one uninterruptible frame.
What these share is that the work is unbounded and the loop has no say in it. The engine cannot pause halfway through a sort to render a frame, because there is no safe point to pause at: your comparator might be holding state. So the only lever you have is to make each frame smaller yourself.
The fix is to break the work into tasks the loop can get between:
function processInChunks(items, handle, chunkSize = 500) {
let i = 0;
function next() {
const end = Math.min(i + chunkSize, items.length);
for (; i < end; i++) handle(items[i]);
if (i < items.length) setTimeout(next, 0);
}
next();
}
Each chunk is its own macrotask, so the loop can render, run timers and handle clicks between them. The total work takes slightly longer and the page stays responsive throughout, which is nearly always the better trade.
For genuinely heavy computation there is a better answer:
// A Web Worker runs on its own thread with its own stack.
// const worker = new Worker("sort.js");
// worker.postMessage(millionItems);
// worker.onmessage = (e) => render(e.data);
// The main thread stays free. This is the only way to get real
// parallelism in the browser; everything else in this unit is ordering.
Any single frame over about 50 milliseconds is felt as lag, and over 16 milliseconds it has already cost you a frame at 60fps. When a page feels sticky rather than slow, look for one long synchronous operation rather than for many small ones, because it is almost always a single frame that is too big.
EXERCISE
2Starvation: A Queue That Never Empties
Microtasks are drained completely, and a microtask that queues another microtask means completely never arrives.
Blocking is easy to picture. Starvation is subtler and produces the same frozen page from the opposite direction.
The loop that cannot be escaped:
function starve() {
Promise.resolve().then(starve);
}
setTimeout(() => console.log("I will never run"), 0);
starve();
// The page freezes. No timer, no click, no render, ever.
There is no long-running frame here. Each callback is trivial and returns immediately. The problem is that the loop drains the microtask queue completely before doing anything else, and this queue is never empty, because every drain adds another entry.
Compare with the same shape using a timer:
function polite() {
setTimeout(polite, 0);
}
setTimeout(() => console.log("I do run"), 0);
polite();
// This is fine. Each iteration is one macrotask, and the loop
// renders and runs other work between them.
Identical recursion, completely different behaviour, because of which queue it lands in. This is the practical consequence of the drain rule: the microtask queue's priority is also its danger.
It rarely appears this obviously. It appears like this:
async function pollUntilReady() {
const status = await check();
if (status !== "ready") {
return pollUntilReady(); // if check() resolves synchronously,
} // this never yields
return status;
}
If check ever returns an already-resolved promise, the recursion stays entirely in the microtask queue and the page locks. The fix is to force a macrotask between attempts:
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function pollUntilReady() {
let status = await check();
while (status !== "ready") {
await delay(200); // a real macrotask, so the loop breathes
status = await check();
}
return status;
}
And the general shape of the fix:
// Recursion that must keep going: use a macrotask to yield.
// setTimeout(next, 0)
// await new Promise(r => setTimeout(r, 0))
//
// Recursion that should finish quickly: make sure it terminates,
// and keep it in microtasks for the speed.
Pro Tip: The tell for starvation is a frozen page with no long function in the profiler, because there isn't one. Thousands of short microtasks look like nothing in a flame chart. If a page locks and the stack looks idle, suspect a promise chain that re-queues itself rather than a slow function.
EXERCISE
3Yielding on Purpose
Between blocking everything and chunking by hand, the platform offers a few ways to hand control back deliberately.
with setTimeout works and has two costs: the 4ms clamp from the next lesson, and no say in when the browser comes back to you. There are better tools when you need them.
requestAnimationFrame: run just before the next paint.
let x = 0;
function step() {
x += 2;
box.style.transform = `translateX(${x}px)`;
if (x < 300) requestAnimationFrame(step);
}
requestAnimationFrame(step);
The callback runs once per frame, synchronised with the browser's repaint, which is roughly every 16ms on a 60Hz display. Using setTimeout(step, 16) instead would out of step with the paint cycle and produce visible stutter. For anything that moves on screen, this is the correct tool.
It also pauses automatically in a background tab, which is usually what you want for animation and never what you want for a timer.
requestIdleCallback: run when nothing more important is pending.
requestIdleCallback((deadline) => {
while (deadline.timeRemaining() > 0 && queue.length > 0) {
process(queue.pop());
}
}, { timeout: 2000 });
The browser calls you when it has spare time in a frame, and deadline.timeRemaining() tells you how much is left so you can stop before overrunning. The timeout option guarantees it eventually runs even on a busy page. This suits genuinely low-priority work: analytics, prefetching, warming a cache.
And a small helper worth knowing:
const yieldToLoop = () => new Promise((resolve) => setTimeout(resolve, 0));
async function processAll(items) {
for (let i = 0; i < items.length; i++) {
handle(items[i]);
if (i % 500 === 0) await yieldToLoop();
}
}
Awaiting a zero timeout is the simplest way to say "let the loop run" inside an async function. It reads better than a recursive chunker and does the same thing.
Choosing between them: requestAnimationFrame for anything visual, requestIdleCallback for work nobody is waiting for, and a yield helper for a long job that must finish but should not freeze the page.
