What performance issue does this code pattern cause?
const element = document.getElementById('myElement');
for (let i = 0; i < 100; i++) {
element.style.width = `${i}px`;
console.log(element.offsetWidth);
}
This code causes forced synchronous layout (layout thrashing) by repeatedly writing to and then reading layout properties in a loop. Each iteration: 1) Changes the width (triggering a style change), 2) Immediately reads offsetWidth (forcing the browser to compute layout). This creates a read/write cycle that prevents the browser from batching layout calculations, severely impacting performance. To optimize, separate reads and writes: first read all necessary values, then perform all updates. A better approach would be to perform all style changes first, then read layout properties if needed.