button.onclick = function() {
status.textContent = 'Loading...';
// Heavy synchronous computation
const result = processMillionItems(data);
status.textContent = 'Done: ' + result;
};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: 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.