They are different.
Reflow
Reflow (a.k.a Layout) is a process of calculating DOM element's size and position in a web page.
Reflow occurs when:
- an element is added, removed, or updated in the DOM
- modification of the content on the web page
- take measurements of an element such as
offsetHeight or getComputedStyle
- change a CSS style
- resize the browser window, etc.
Whenever you change something in the DOM, browser will re-calculate the positions and dimensions of DOM elements and then repaint the screen.
Layout Thrashing
Reflows are expensive, so browsers try to queue the changes and apply them in batches to minimize the required reflows. This strategy allows the browsers to apply multiple styles and do only one reflow.
If our Javascript code requests the style information by reading properties such as:
offsetTop, offsetLeft, offsetWidth, offsetHeight
scrollTop, scrollLeft, scrollWidth, scrollHeight
clientTop, clientLeft, clientWidth, clientHeight
or by calling getComputedStyle() and if there are any queued changes, in order to provide the latest style information, browser needs to flush all the queued changes, perform the reflow and then provide you the requested style information.
This prevents browsers from optimizing reflows.
This can get even worse if we request and set styles repeatedly in quick succession, for example in a loop:
for (let i = 0; i < 10; i++) {
elements[i].style.width = (container.offsetWidth + 10) + "px";
}
In the above code example, we are continuously reading and changing style information.
This type of code prevents browsers from optimizing reflows because once your code changes the style information and then requests the style information again in the next iteration of the loop, browser has to perform the reflow, provide you the latest style information, and repaint the screen. All this happening inside a loop makes it worse.
This is what's known as layout thrashing because our code will cause the browsers to continuously recalculate the dimensions and positions of the DOM elements.
Above code can be improved by reading the style information only once, just before the loop starts.
const containerWidth = container.offsetWidth;
for (let i = 0; i < 10; i++) {
elements[i].style.width = (containerWidth + 10) + "px";
}
Above code will allow the browser to optimize reflows because we only request the style information once and the changes to the width of the elements inside the loop can be queued and applied in batches, leading to fewer reflows as compared to the previous code example.
Further Reading: