Question presented to candidate: "You have a loop over 200 DOM elements: for each one, you read its current height, then immediately write a new height back. It's noticeably slow. Why, and how would you rewrite it to fix that?"
What a strong answer should cover:
- 📌 Interview term: layout thrashing (forced synchronous reflow) — the real performance problem caused by repeatedly INTERLEAVING a DOM read (like
.offsetHeight) with a DOM write (like.style.height = ...) inside a loop — each read genuinely forces the browser to immediately, synchronously recompute layout for any pending write from the PREVIOUS iteration, rather than batching all the layout work into one pass at the end of the script. - 📌 Interview term: the real, direct, measured proof — verified directly, live in a real browser: interleaving a real read (
box.offsetHeight) then a real write (box.style.height = ...) across 200 real elements averaged ~56.6ms across 5 real runs; the IDENTICAL work restructured to do all reads FIRST, then all writes, averaged ~0.66ms across 5 real runs — a real, measured ~85x slowdown from the interleaved version, not an estimate. - 📌 Interview term: the real fix — batching reads then writes — a precise answer names the concrete restructuring: collect every needed READ value into an array FIRST (in one pass, with no writes interleaved), then perform every WRITE in a SEPARATE, second pass — this lets the browser genuinely defer ALL layout recomputation to a single point, rather than once per iteration.
- 📌 Interview term: why a read specifically forces the synchronous recalc — a precise answer names that properties like
.offsetHeight,.offsetWidth,.getBoundingClientRect(), and.scrollTopgenuinely require an up-to-date, real layout to answer correctly — if a prior write in the same script has invalidated the current layout, the browser genuinely has no choice but to compute it synchronously, right then, before the read can return an answer. - A precise answer names the real, practical alternative for more complex cases: using
requestAnimationFrameto defer writes to the browser's own next natural paint step, or a library like FastDOM that automatically batches reads and writes across a codebase.
Clarifying questions expected:
- None — this is a definitional/practical question; directly diagnosing the prompt's own described slowness with real, measured proof is the strong signal.
Code / implementation expected: Yes — a real, timed, side-by-side comparison of the interleaved (thrashing) version against the batched version, executed against real DOM elements.