In the mozilla docs on performance best practices for front-end engineers it's remended to bine setTimeout
with requestAnimationFrame
to run something immediately after a repaint:
requestAnimationFrame(() => {
setTimeout(() => {
// This code will be run ASAP after Style and Layout information have
// been calculated and the paint has occurred. Unless something else
// has dirtied the DOM very early, querying for style and layout information
// here should be cheap.
}, 0);
});
Why is this the remended solution? What exactly makes this the optimal way to schedule something right after a repaint?
In the mozilla docs on performance best practices for front-end engineers it's remended to bine setTimeout
with requestAnimationFrame
to run something immediately after a repaint:
requestAnimationFrame(() => {
setTimeout(() => {
// This code will be run ASAP after Style and Layout information have
// been calculated and the paint has occurred. Unless something else
// has dirtied the DOM very early, querying for style and layout information
// here should be cheap.
}, 0);
});
Why is this the remended solution? What exactly makes this the optimal way to schedule something right after a repaint?
Why is this the remended solution? What exactly makes this the optimal way to schedule something right after a repaint?
Running code immediately after a repaint maximizes the chance that the DOM has been fully calculated, and thus minimizes the chance that querying the dom will cause a costly reflow. If you're not querying the dom anyway, then this isn't something you need to worry about.
requestAnimationFrame will schedule code to run immediately before the repaint, which is close to where you want to be but not quite. So then doing a setTimeout
of 0 (or setImmediate
on browsers that support it) will execute code as soon as it can after that. This won't guarantee that your code is the first thing to run after the repaint, but it's the best you can do given the apis at your disposal.