CodeZettaInterview Hub

JavaScript · Event Loop · Senior · Debugging

How can promise microtasks starve the event loop, and how do you fix it?

Short Interview Answer

A chain that continually queues new microtasks never reaches the next macrotask/render; break work into macrotasks or use schedulers/idle time.

Detailed Explanation

Example: a recursive `Promise.resolve().then(processNext)` draining a huge queue will keep the microtask queue non-empty, delaying timers and paint. Fix by batching N items per turn, then `setTimeout(0)`/`postMessage`/`scheduler.postTask` to yield. Similarly, huge sync loops block entirely. Prefer streaming/chunking algorithms. In Node, be aware of `nextTick` loops as well. Diagnose with frozen UI and delayed timeouts despite 'async' code.

Example

async function drain(queue) {
  while (queue.length) {
    queue.shift()();
    if (queue.length % 100 === 0) {
      await new Promise((r) => setTimeout(r, 0)); // yield
    }
  }
}

Interview Tip

Connect to real UI freeze incidents.

Common Mistake

Assuming anything with promises is non-blocking for the UI.

Did you know this answer?