🟑 MediumEvent Loop TrapsπŸ› Debug Challenge

UI update blocked by sync code

Buggy Code β€” Can you spot the issue?

button.onclick = function() {
  status.textContent = 'Loading...';

  // Heavy synchronous computation
  const result = processMillionItems(data);

  status.textContent = 'Done: ' + result;
};

Fixed Code

button.onclick = function() {
  status.textContent = 'Loading...';

  // Yield to browser with setTimeout(0) to allow repaint
  setTimeout(() => {
    const result = processMillionItems(data);
    status.textContent = 'Done: ' + result;
  }, 0);
};

// Better for truly heavy work: use Web Worker
// const worker = new Worker('worker.js');
// worker.postMessage(data);
// worker.onmessage = e => status.textContent = 'Done: ' + e.data;

Bug Explained

Bug: The browser can't repaint between the textContent assignments because JS is single-threaded. The sync computation blocks the event loop β€” the UI freezes.

Explanation: setTimeout(0) yields control back to the browser event loop, allowing it to repaint ("Loading...") before resuming the heavy computation.

Key Insight: setTimeout(0) yields to the browser for repaints. For genuinely heavy computation, use Web Workers to avoid blocking the main thread entirely.

More Event Loop Traps Debug Challenges

πŸ”΄ HardMicrotask starvation β€” UI never updatesβ†’πŸŸ‘ MediumsetTimeout inside a loop β€” all fire at onceβ†’πŸ”΄ HardGenerator function called synchronously inside Promiseβ†’πŸŸ‘ MediumMixing microtasks and DOM updatesβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab