The hidden cost
The browser keeps a pending list of style changes and computes layout lazily. But reading a property like offsetHeight forces it to flush that work immediately so the value is correct.
Thrashing defined
Layout thrashing happens when code interleaves reads and writes in a loop. Each write invalidates layout, and the next read forces a synchronous reflow. A loop of read, write, read, write triggers many full layouts.
The fix is batching
Separate the phases. Do all reads first while layout is fresh, then do all writes. The browser flushes layout once instead of once per iteration.
- Cache measured values in variables.
- Apply all style changes together after reading.
- Let writes coalesce into a single layout pass.
Tools that help
Scheduling writes inside requestAnimationFrame aligns them with the paint cycle. Libraries that split read and write phases automate this batching pattern.
Key idea
Layout thrashing comes from interleaving reads and writes that force repeated reflows; batch all reads then all writes so layout flushes once.