Track 02 · Lesson 11 of 17Inside the browser

Track 02 · Inside the browser

Don't block the main thread

Lesson 11 of 17· 6 min

While JavaScript runs, the browser can't paint or respond to clicks. A long task freezes the whole page. Watch the dot, which is moved by JavaScript, then run the same amount of work in one go and in small chunks.

Freeze it, then don't

The first button really freezes this page for 1.5 seconds

Frame times: tall red stems are frames the browser couldn’t draw on time

– ms

Longest frozen frame

– s

Total time

// One long task: nothing else can happen until it ends
function processAll(items) {
  for (const item of items) heavyWork(item);
}

// Same work in chunks: the browser can paint and handle input in between
async function processInChunks(items) {
  for (let i = 0; i < items.length; i++) {
    heavyWork(items[i]);
    if (i % 100 === 0) await new Promise((r) => setTimeout(r, 0));
  }
}
// For really heavy jobs, move the work to a Web Worker instead.

Why the page froze#

Painting, handling clicks and running your JavaScript all happen on the same thread, the main thread, one task at a time. That's the event loop from the last lesson: while one task runs, nothing else gets a turn. A 1.5-second loop is one 1.5-second task, so the dot can't move and your typing waits.

Any task over 50 ms counts as a long task. To users, anything over about 100 ms already feels sluggish, and Core Web Vitals counts interactions slower than 200 ms against you. That's the next-but-one lesson.

Three ways out#

  • Chunk it. Do a slice of work, then yield with await new Promise((r) => setTimeout(r, 0)) or scheduler.yield() where it's supported, so the browser can paint and handle input in between.
  • Do less. Debounce expensive handlers, and avoid recalculating what hasn't changed.
  • Move it off the main thread. A Web Worker runs JavaScript on a separate thread, perfect for parsing large files or processing images.

Check yourself

A button handler runs a loop that takes 800 ms. What happens to the page meanwhile?