Sub topic 15
Blocking the Loop and Starving It with Microtasks
This chapter assumes you know how one turn of the event loop works: one task runs, the microtask queue is drained, and then the browser may render. It also assumes you can read code that uses setTimeout, promises, and queueMicrotask.
Two Ways to Freeze an App
The event loop can only move forward when the call stack is empty. There are two common ways to stop it from moving:
- Blocking. A single piece of synchronous code runs for a long time. Nothing else can run until it returns.
- Microtask starvation. Each microtask schedules another microtask. The microtask queue never empties, so the loop never reaches the next task or the next render.
To the user, both look the same: clicks do nothing, animations stop, and timers fire late. A Node.js server has the same problem. It stops accepting requests and answering them.
Blocking with Synchronous Work
Long loops, large JSON.parse calls, synchronous file reads, and heavy regular expressions all hold the call stack.
const start = Date.now();
setTimeout(() => {
console.log('timer fired after', Date.now() - start, 'ms');
}, 10);
// Simulate expensive synchronous work: about 500 ms
let total = 0;
while (Date.now() - start < 500) {
total += Math.sqrt(total + 1);
}
console.log('work done');
// Output:
// work done
// timer fired after ~500 msThe timer expired after 10 ms, but its callback could not run until the stack was empty. In a browser, no rendering or input handling happens during those 500 ms either.
Starving the Loop with Microtasks
Starvation is easier to miss because no single callback is slow. The rule that causes it is that the engine drains the microtask queue completely, including any microtasks added while it is draining.
let count = 0;
setTimeout(() => console.log('timer ran after', count, 'microtasks'), 0);
function spin() {
if (count++ < 1_000_000) {
queueMicrotask(spin);
}
}
spin();
// Output: timer ran after 1000001 microtasksEvery spin call is quick, but the timer waits for all one million of them. If you remove the limit, the timer never runs and the page never repaints. A recursive .then() chain or an async function that loops on await with already-resolved values behaves the same way.
Tasks Do Not Starve the Loop
If you schedule the next step with setTimeout instead, each step becomes a separate task. Between tasks, the loop drains microtasks, can render, and can run other tasks that are waiting.
| Scheduling method | Can other tasks run between steps? | Can the browser render between steps? |
|---|---|---|
| Plain `while` loop | No | No |
| Recursive `queueMicrotask` or `.then()` | No | No |
| Recursive `setTimeout` | Yes | Yes |
Diagnosing the Problem
- In browser DevTools, the Performance panel marks long tasks (over 50 ms) with a red corner.
- A timer that fires much later than its delay is a sign that the loop is blocked.
- In Node.js,
perf_hooks.monitorEventLoopDelay()measures how late the loop is running.
Exercise
A function processes a queue by calling Promise.resolve().then(processNext) after each item. With 50,000 items, the page freezes until all of them are done, even though each item takes only microseconds. Why, and what one-line change lets the page render between items?
Show answer
Each .then callback is a microtask that queues the next microtask, so the microtask queue never empties until the last item is done. Rendering and other tasks have to wait until then. Scheduling the next step as a task with setTimeout(processNext, 0) lets the loop render and handle input between items. Processing a batch of items per task keeps the overhead low.