requestAnimationFrame()
const id = requestAnimationFrame(function(time))
Calls a function just before the browser repaints the page (usually 60 times a second or more). It is the right way to do animations in JavaScript.
Parameters
- function(time) – gets the time in milliseconds (like
performance.now()).
Return value
The ID for cancelAnimationFrame(id).
Examples
<div id="progress" style="width: 0; height: 8px; background: #09f"></div>
const progress = document.querySelector('#progress');
const duration = 200;
await new Promise((done) => {
let start;
const step = (time) => {
start ??= time;
const share = Math.min((time - start) / duration, 1);
progress.style.width = share * 100 + '%';
if (share < 1) requestAnimationFrame(step);
else done();
};
requestAnimationFrame(step);
});
console.log(progress.style.width);
Output:
100%
Things to watch out for
- The function is called only once – for the next frame call it again (see the example).
- Count with the elapsed time, not with the number of frames – screens have 60, 120 or 144 Hz.
- In an inactive tab it is not called at all. Simple transitions and animations are better done in CSS.
Browser support
Baseline – widely available: works in all major browsers and has for a long time (since 2015 at the latest). Since version: Chrome 24, Firefox 23, Safari 7; not in Node.js (a browser API). As of October 2026 (MDN browser-compat-data).