JavaScript often triggers visual changes. Sometimes that's directly through style manipulations, and sometimes it's calculations that result in visual changes, like searching or sorting data. Badly-timed or long-running JavaScript is a common cause of performance issues. You should look to minimize its impact where you can.
JavaScript often triggers visual changes. Sometimes that's directly through style manipulations, and sometimes it's calculations that result in visual changes, like searching or sorting data. Badly-timed or long-running JavaScript is a common cause of performance issues. You should look to minimize its impact where you can.
JavaScript performance profiling can be something of an art, because the JavaScript you write is nothing like the code that is actually executed. Modern browsers use JIT compilers and all manner of optimizations and tricks to try and give you the fastest possible execution, and this substantially changes the dynamics of the code.
With all that said, however, there are some things you can definitely do to help your apps execute JavaScript well.
Summary
- Avoid setTimeout or setInterval for visual updates; always use requestAnimationFrame instead.
- Move long-running JavaScript off the main thread to Web Workers.
- Use micro-tasks to make DOM changes over several frames.
- Use Chrome DevTools’ Timeline and JavaScript Profiler to assess the impact of JavaScript.
Use requestAnimationFrame for visual changes
When visual changes are happening on screen you want to do your work at the right time for the
browser, which is right at the start of the frame. The only way to guarantee that your JavaScript
will run at the start of a frame is to use requestAnimationFrame.
/**
* If run as a requestAnimationFrame callback, this
* will be run at the start of the frame.
*/
function updateScreen(time) {
// Make visual updates here.
}
requestAnimationFrame(updateScreen);
Frameworks or samples may use setTimeout or setInterval to do visual changes like animations,
but the problem with this is that the callback will run at some point in the frame, possibly right
at the end, and that can often have the effect of causing us to miss a frame, resulting in jank.