Syntax
const id = requestAnimationFrame(timestamp => { /* draw */ });
cancelAnimationFrame(id);Examples
Animating with requestAnimationFrame: working example
Run this standalone example in a modern browser console unless another environment is specified. Expected result: In a visible browser page, a blue square moves 120 pixels right over roughly one second and logs Finished.
const box = document.createElement("div");
box.style.cssText = "width:30px;height:30px;background:royalblue";
document.body.append(box);
let start;
function frame(time) {
start ??= time;
const progress = Math.min((time - start) / 1000, 1);
box.style.transform = `translateX(${progress * 120}px)`;
if (progress < 1) requestAnimationFrame(frame);
else console.log("Finished");
}
requestAnimationFrame(frame);- Expected result: In a visible browser page, a blue square moves 120 pixels right over roughly one second and logs Finished.
- Each callback requests the next frame only while work remains.
- Elapsed timestamps determine progress, so faster displays do not make the animation run faster.
Best practices
- Cancel pending animation callbacks during component cleanup.
- Respect reduced-motion preferences in production animation interfaces.
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification