JavaScript·100 questions

What is requestAnimationFrame?

Answer

The requestAnimationFrame method is a specialized API in JavaScript created specifically for smoothly implementing visual animations in a web browser. Its main difference from the classic setInterval is that it is tightly synchronized with the monitor's screen refresh rate, which on most modern displays is 60 frames per second (fps), and on advanced devices can reach 120 Hz and higher.

When you pass a callback function to requestAnimationFrame, the browser guarantees that the animation code will execute right before the next page repaint. This helps avoid unpleasant effects such as lag, stuttering, and frame tearing, which often occur when trying to animate elements at fixed time intervals. The method returns a numeric request identifier that can be passed to the cancelAnimationFrame function if the animation needs to be aborted before its completion, such as when closing a modal window.

Another crucial advantage of requestAnimationFrame is its energy efficiency and care for system performance. If the user switches to another browser tab or minimizes the window, the browser automatically pauses the execution of all animations tied to this method. This allows for a radical reduction in CPU load, battery savings on mobile devices, and prevention of hardware overheating, whereas setInterval would continue to uselessly burden the system in the background.

Was this answer helpful?

More questions in this topic

Related questions from other topics