Window requestAnimationFrame() Method
Example
Use of the requestAnimationFrame() method:
const adiv = document.getElementById('mydiv');
let leftpos = 0;
function movediv(timestamp){
leftpos += 5;
adiv.style.left = leftpos + 'px';
requestAnimationFrame(movediv);
}
requestAnimationFrame(movediv);
Try it Yourself »
Description
The requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.
Note: Your callback routine must itself call requestAnimationFrame() if you want to animate another frame at the next repaint.
Tip: You should call this method whenever you are ready to update your animation onscreen because:
- The browser can optimize it, so animations will be smoother
- Animations in inactive tabs will stop, allowing the CPU to chill
- More battery-friendly
Browser Support
Method | |||||
---|---|---|---|---|---|
requestAnimationFrame() | 24.0 | 10.0 | 23.0 | 6.1 | 15.0 |
Syntax
requestAnimationFrame(callback)
Parameter Values
Parameter | Type | Description |
---|---|---|
callback | String | Required. A function to call when it is time to update your animation for the next repaint. The callback has one single argument, a DOMHighResTimeStamp, which indicates the current time (the time returned from performance.now() ) for when requestAnimationFrame() starts to fire callbacks |
Technical Details
Return Value: | A long integer. The request id, that uniquely identifies the entry in the callback list. You can pass this value to window.cancelAnimationFrame() to cancel the refresh callback request |
---|
Related Pages
Window Object: cancelAnimationFrame() Method
❮ Window Object