Registers a function to call when the system is ready to update (repaint) the display. This provides smoother animations and optimal power efficiency by allowing the system to determine when the animation occurs. The visibility of the web application and the display refresh rate are used to determine the appropriate speed of the animations, e.g. the number of frames per second supported by the system. . For example, if the web application isn't visible, the browser will stop painting the animation by not calling the registered function.
Syntaxvar handle = window.requestAnimationFrame(callback);
- callback [in]
The animation code to be run when the system is ready.
A handle or ID to the requestAnimationFrame method that can be used to cancel the request if needed.
Unlike older animation techniques based on setTimeout and setInterval methods which required developers to make assumptions on when to schedule the next frame of animation, requestAnimationFrame requestAnimationFrame simplifies animations by scheduling the next animation frame only when the system is ready to paint. This leads to smoother animations and less power consumption than previous animation techniques because requestAnimationFrame takes the visibility of the web application and the refresh rate of the display into account.
The requestAnimationFrame method only schedules a single callback, like setTimeout method. To schedule subsequent animation frames, the requestAnimationFrame method must be called again from within the callback function.
To cancel an animation request before the animation function is called back, use cancelAnimationFrame. It's a good practice to stop calling requestAnimationFrame at that time as well.
The following example shows several functions that demonstrate how to use requestAnimationFrame to create an animation, and cancelAnimationFrame to stop it.
The example starts by creating a <div> element and a start and stop button. When the page finishes loading (<body onload=...>), it initiates the elm variable. The elm variable is the ID of the <div> element.