Batch Layout Reads And Writes Per Frame

Interleaving layout reads and writes forces synchronous reflows; batching all getBoundingClientRect calls before style writes keeps one layout per frame.

TypescriptData Fetching

Code

typescriptsnippet
24 lines
// Alternating layout reads and writes forces synchronous reflow: batch all reads first, then all writes -
// requestAnimationFrame is the natural batch boundary
function resizeCards(cards: HTMLElement[], scale: number): void {
  // Read phase: grab every current width in one go, no writes in between
  const widths = cards.map((card) => card.getBoundingClientRect().width);

  // Write phase: apply the styles in bulk so the browser lays out once
  cards.forEach((card, index) => {
    card.style.width = `${Math.round(widths[index] * scale)}px`;
  });
}

const cards = Array.from(document.querySelectorAll<HTMLElement>('.card'));

// Every frame reads first, writes second; interleaving them in one callback doubles the reflow count
requestAnimationFrame(() => resizeCards(cards, 0.8));
console.log('resize scheduled for next frame:', cards.length, 'cards');

// Anti-pattern for contrast: read then write per element - n elements trigger n synchronous layouts
function thrash(cards: HTMLElement[], scale: number): void {
  for (const card of cards) {
    card.style.width = `${Math.round(card.getBoundingClientRect().width * scale)}px`;
  }
}

What the code does

Beyond resizeCards and thrash, the file defines no other functions; the batching story lives in those two.

Repetition shows up in exactly one place: the for (const card of cards) loop.

Points of care

  • document and requestAnimationFrame are browser APIs; Node exposes neither, so this belongs in a page.

Applying it

Entry signature: function resizeCards(cards: HTMLElement[], scale: number)

The demo output is labeled (resize scheduled for next frame:), so every printed line ties back to the operation behind it.

Statements that matter

const widths = cards.map((card) => card.getBoundingClientRect().width);
requestAnimationFrame(() => resizeCards(cards, 0.8));
cards.forEach((card, index) => {
card.style.width = `${Math.round(widths[index] * scale)}px`;
});

Interactive Tools for This Topic

FAQ

Does Batch Layout Reads And Writes Per Frame run in plain Node.js?
No — it touches `document` and `requestAnimationFrame`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.