CS Fundamentals Trainer · JavaScript · Performance & Memory

Why is this loop slow for 1,000 boxes, and what fixes it?

for (const box of boxes) {
  box.style.width = box.parentElement.offsetWidth / 2 + 'px';
}
  1. `offsetWidth` makes the browser recompute styles for the entire document on every read; caching each value in `localStorage` avoids it.
  2. Building strings with `+ 'px'` allocates many temporary strings; switching to template literals removes the slowdown.
  3. Each style write triggers an immediate repaint; wrapping the loop body in `setTimeout(..., 0)` batches the paints together.
  4. Each style write invalidates layout, so the next `offsetWidth` read forces a synchronous layout; read all widths first, then write all styles.

Difficulty: medium

Answer this question

Related questions