Why does a long synchronous function block UI updates and event handling?
Short answer
Since JS runs on one thread shared with rendering and input handling, any synchronous code that takes a long time to finish prevents the browser from processing clicks, repainting the screen, or running queued callbacks until that function returns.
Advertisement
AModel answer
Since JS runs on one thread shared with rendering and input handling, any synchronous code that takes a long time to finish prevents the browser from processing clicks, repainting the screen, or running queued callbacks until that function returns.
function blockFor(ms) {
const end = Date.now() + ms;
while (Date.now() < end) {} // busy-waits, freezing the page
}
blockFor(3000); // UI is frozen for 3 secondsReal-world example
Diagnosing a frozen 'Not Responding' UI caused by a synchronous JSON.parse() on a huge payload.
Likely follow-ups
- How would you break up a long synchronous task to avoid blocking the UI?
Related topics