Layout Thrashing and Forced Reflows
You'll learn: How repeatedly reading and then writing layout properties in JavaScript creates performance bottlenecks by forcing the browser to recalculate styles and layout synchronously.
What Is Layout Thrashing?
Layout thrashing (also called "forced synchronous layout") happens when your JavaScript reads a layout property (like offsetHeight or getBoundingClientRect()), then immediately writes a style change, then reads again, then writes again—all in a tight loop.
Here's the problem: when you read a layout property, the browser must ensure its answer is accurate. If you've just made style changes, the browser is forced to stop everything and recalculate layout right then, even though it would normally batch these calculations for efficiency.
The Performance Impact
Think of it like constantly asking someone "How tall are you?" while they're putting on and taking off shoes. They have to stop, measure, answer, then you change their shoes again and ask again. Exhausting and slow!
Each forced reflow can take milliseconds, but in a loop processing dozens or hundreds of elements, this compounds into visible jank and frame drops.
How to Detect It
In the Performance Panel, look for purple "Layout" bars that appear in rapid succession or during JavaScript execution. The Performance DevTools will often warn you with "Forced reflow" annotations when it detects this pattern.
The solution? Batch your reads, then batch your writes. Read all the layout properties you need first, store them, then apply all your style changes afterward.
Key Takeaway: Layout thrashing occurs when you alternate between reading layout properties and writing styles, forcing the browser to recalculate layout synchronously multiple times—always separate your reads from your writes to avoid this performance killer.