Microtask Starvation
What you'll learn: How creating endless microtasks can prevent other code from running and freeze your application.
The Problem with Infinite Microtasks
Remember that microtasks always run before tasks in each event loop tick? This is powerful, but dangerous. If you keep queueing new microtasks inside microtasks without ever stopping, the event loop will never move on to tasks. This means:
- UI updates won't render
- User interactions won't respond
- Timers won't fire
- The browser appears frozen
This condition is called microtask starvation — tasks are "starved" of execution time because microtasks hog the event loop.
How It Happens
function starveTheBrowser() {
console.log('Queuing a microtask');
queueMicrotask(() => {
starveTheBrowser(); // Queues another microtask immediately!
});
}
starveTheBrowser();
// The browser is now frozen. Tasks never run.
This creates an infinite chain: each microtask queues another microtask. Since the event loop processes all microtasks before moving to tasks, it never gets a chance to render, handle clicks, or run setTimeout callbacks.
The Real-World Impact
Even non-infinite chains can cause problems if they're long enough:
for (let i = 0; i < 10000; i++) {
queueMicrotask(() => console.log(i));
}
// 10,000 microtasks must complete before any task runs
The UI will be unresponsive until all 10,000 microtasks finish.
Prevention
Always ensure microtask chains eventually terminate. If you need repeated work, use tasks (like setTimeout) occasionally to let the browser breathe and process user interactions.
Key Takeaway: Infinite or excessively long microtask chains block the event loop from processing tasks, freezing UI updates and user interactions — always ensure microtask chains have a clear endpoint.