requestAnimationFrame()
Example
function step() {
x += 2;
box.style.transform = `translateX(${x}px)`;
requestAnimationFrame(step);
}
requestAnimationFrame(step);let start;
function step(time) {
start ??= time;
const x = Math.min((time - start) * 0.1, 300);
box.style.transform = `translateX(${x}px)`;
if (x < 300) requestAnimationFrame(step);
}
requestAnimationFrame(step);Position depends on elapsed time, so speed is the same at any refresh rate, and the loop ends at the target.
Common mistakes
- Moving an element a fixed number of pixels per frame, so it runs faster on 120 Hz screens.
- Expecting callbacks to keep running in a background tab, where browsers pause them.
Key points
- Movement uses the callback's timestamp to compute elapsed time, not a fixed step per frame.
- The ID is stored and the loop is stopped with
cancelAnimationFrame()or an end condition. - Simple effects use CSS
transitionoranimationinstead of a JS loop. - The animation respects
prefers-reduced-motion.
Interview questions
requestAnimationFrame vs setInterval: which is better for animation?
requestAnimationFrame(). It runs in step with the screen refresh and pauses in hidden tabs, while setInterval() can drop or double frames.
How often does requestAnimationFrame() run?
Usually once per screen refresh: about 60 times per second on a 60 Hz display, and more often on faster screens.