Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 5 · Concept · 20 min · revision 3

The Main Thread, Long Tasks and Layout Thrashing

Explain why one busy task freezes the whole interface, measure a long task and a forced synchronous layout from code, and cut both down by slicing work and batching reads and writes.

Contentsand lesson path

What you will learn

  • Explain why long tasks on the main thread freeze the UI and how interleaved DOM reads and writes force extra style and layout work.

01. Why it matters

A page can look finished and still feel broken. You click a Sort button and, for a moment, nothing happens: no hover effects, no typing, no scrolling. Then the answer appears all at once. The cause is almost never the network and rarely the rendering stages from the previous lessons — it is one task that held the main thread for too long. This lesson shows you what a task is, how to see one from code, and how the most common main-thread habit in JavaScript code — interleaving layout reads with style writes — multiplies the browser's work.

02. One thread, one task at a time

In every tab, one thread does nearly all of the work you have learned about: running your JavaScript, recalculating styles, laying out, painting, and dispatching input events. Work arrives as tasks — a click handler, a timer callback, the parse of a chunk of HTML — and each task runs to completion. While a task runs, nothing else on that thread can happen. Clicks and key presses still occur in the world, but their handlers queue up behind the running task and only execute when it finishes. That queueing delay is what a user experiences as jank or freeze.

A task that runs longer than 50 ms is a long task — the threshold comes from the Long Tasks API, because 50 ms is about the budget within which an interface still feels immediate. (The Long Tasks API is available only in Chromium-based browsers, and so is its newer companion for diagnosis, the Long Animation Frames API. scheduler.yield(), met below, is a different tool: it lets your own code pause and resume, and it ships in Chromium 129+ and Firefox 142+ but not yet in Safari.) The API reports long tasks to a PerformanceObserver, so you can see them from code without opening a panel:

JavaScript · longtask.html — one busy loop, watched by an observer
// Any task over 50 ms counts as a long task. Register the observer
// first, so it sees the task the busy loop is about to create.
let longTasks = 0;
new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    longTasks += 1;
    console.log('long task: ' + Math.round(entry.duration) + ' ms');
  }
}).observe({ type: 'longtask', buffered: true });

function busy(ms) {
  const end = performance.now() + ms;
  while (performance.now() < end) {
    // stand-in for real work: sorting and reducing a data set
  }
}

setTimeout(() => busy(250), 0);
Illustrative output (our run; the report can arrive a moment after the task)
long task: 250 ms

The fix for a long task is to slice it. setTimeout hands control back to the event loop between chunks, and the browser spends those gaps dispatching input, painting, and running everything else that queued up. Each chunk stays under the 50 ms budget, so the same total work stops being visible as a freeze. This runs in the same page as the snippet above, reusing busy and resetting the longTasks counter:

JavaScript · the same 250 ms, sliced into short tasks
longTasks = 0;
let remaining = 250;
(function chunk() {
  const slice = Math.min(30, remaining); // 8 × 30 ms, then 10 ms
  busy(slice);
  remaining -= slice;
  if (remaining > 0) {
    setTimeout(chunk, 0);
  } else {
    console.log('done. long tasks seen: ' + longTasks);
  }
})();
Expected output
done. long tasks seen: 0

The same total work now runs in nine short tasks, and the observer has nothing to report. Slicing with setTimeout, or with scheduler.yield() where the browser has it, is the lightweight fix; for work that is genuinely CPU-heavy and independent of the DOM, a Web Worker moves it to another thread entirely — web.dev's guide to optimising long tasks compares the two strategies.

03. Forced synchronous layout and layout thrashing

The second habit is subtler and hides inside ordinary-looking code. Remember from the pipeline lesson that layout is a stage: it computes geometry once, and the browser keeps the result until something invalidates it. Writing a style marks the layout as dirty — it does not recompute anything yet. But reading geometry (properties such as offsetWidth, or values from getBoundingClientRect) needs a correct answer, so if the layout is dirty at that moment, the browser must run layout right then, synchronously, before it can return the value. That is a forced synchronous layout.

Interleave reads and writes in a loop and you force one layout per iteration. That pattern has a name — layout thrashing — and it is common because it looks harmless. The demo page below sets up 240 cards in a flex list and measures styling them two ways: first one read and one write at a time, then with the reads and writes batched:

JavaScript · thrash.html — 240 cards, two ways of writing the same loop
// Interleaved: one geometry read and one style write per card.
function thrash() {
  for (const card of cards) {
    const parentWidth = card.parentElement.offsetWidth; // read
    card.style.width = parentWidth / 3 - 12 + 'px'; // write
  }
}

// Batched: all the reads first, then all the writes.
function batched() {
  const widths = cards.map((card) => card.parentElement.offsetWidth);
  cards.forEach((card, i) => {
    card.style.width = widths[i] / 3 - 12 + 'px';
  });
}

const thrashStart = performance.now();
thrash();
const thrashMs = Math.round(performance.now() - thrashStart);
const batchStart = performance.now();
batched();
const batchMs = Math.round(performance.now() - batchStart);
console.log('interleaved, 240 cards: ' + thrashMs + ' ms');
console.log('batched, same 240 cards: ' + batchMs + ' ms');
Illustrative output (one run in headless Chromium 156; your numbers will differ)
interleaved, 240 cards: 78 ms
batched, same 240 cards: 1 ms

Same cards, same styles, same final widths: 78 ms against 1 ms in this run. The interleaved loop forces a fresh layout before every read: 240 layouts instead of 1, and in this run each one cost about a third of a millisecond. Two more consequences follow from the same mechanism. First, the interleaved loop is itself a long task: in the lab page that uses this pattern, the browser reports a single task of roughly a third of a second that contains the busy loop and all the forced layouts. Second, the cost is set by reads that follow writes, not by how many elements you style: a geometry read after any style write makes the browser bring every dirty part of the layout up to date before it answers, which is usually far more than the element you touched unless CSS containment (contain: layout) keeps the change local. web.dev's article on avoiding layout thrashing shows the same fix from the rendering side.

04. Keeping the main thread cheap

Three habits cover most of what this lesson measured. Batch geometry reads before writes, so the browser lays out once instead of once per read. Slice long-running JavaScript into tasks under 50 ms, so the event loop can serve input between them. And prefer changes the compositor can handle alone — transform and opacity — when you animate, so a smooth animation does not schedule layout and paint for every frame. The Performance panel is where you confirm all three: its flame chart shows which function ate the task, and forced reflows appear as Layout events nested inside your JavaScript. The lab in this skill walks that recording end to end.

05. Check your understanding

Practice check · 3 questions

Main thread in practice

Three judgements about tasks, layouts and fixes.

Q1. A click handler starts a 120 ms calculation. The user clicks again 40 ms in. When does the second click run?
Q2. Which API reports long tasks from code, without any panel open?
Q3. The batched loop ends with 240 style writes and reports 1 ms. When does the browser compute the layout those writes need?
Practice only: not graded, not saved, not evidence.

06. Apply it

Audit a piece of interactive code you own — a filter, a sort, a resize handler. Read it twice: once marking every geometry read (offsetWidth, offsetHeight, getBoundingClientRect, getComputedStyle when you need layout values), and once marking every write (style assignments, class changes, DOM insertions). If any read sits after a write inside the same function, restructure so the reads all come first, then measure before and after with performance.now() around the function, exactly as the demo did. If any single call can exceed 50 ms, slice it — and if the work never touches the DOM, consider a worker. The lab gives you a page with all three problems to practise on.

07. Review prompt

Without looking back: what is a task, and why does one long task freeze input? What threshold defines a long task, and which API reports it? Explain what a forced synchronous layout is, why reading offsetWidth right after writing a style causes one, and what batching changes about the number of layouts. Finally, name the two properties that usually avoid layout and paint altogether.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check