requestAnimationFrame Explained (With Examples)
Contents
- The basic syntax
- The animation loop
- Smooth on every screen: use delta time
- Frame-rate independent animation
- Animate over a fixed duration
- Stop an animation with cancelAnimationFrame
- Beyond animations
- Throttle scroll and resize handlers
- Wait for the browser to paint (double rAF)
- requestAnimationFrame vs setTimeout and setInterval
- When CSS is the better choice
- FAQ
requestAnimationFrame() asks the browser to run a function right before it paints the next frame. That makes it the right tool for anything that changes on screen every frame in JavaScript: animations, games, canvas drawing, and smooth scroll effects.
It runs once per screen refresh (60 times a second on most screens, 120 on many phones and newer laptops), pauses automatically in background tabs, and keeps your updates in sync with what the browser draws, so there’s no stutter.
The basic syntax
Pass it a callback. The browser calls it once, before the next repaint, and passes a high-resolution timestamp in milliseconds. It returns an ID you can use to cancel it.
const id = requestAnimationFrame((timestamp) => {
console.log('About to paint, at', timestamp, 'ms');
});
The animation loop
requestAnimationFrame runs your function only once. To animate, the function requests the next frame itself, creating a loop that runs for as long as you need it.
const box = document.querySelector('.box');
let x = 0;
function frame() {
x += 2;
box.style.transform = `translateX(${x}px)`;
if (x < 300) {
requestAnimationFrame(frame); // schedule the next frame
}
}
requestAnimationFrame(frame);
Smooth on every screen: use delta time
The loop above has a hidden bug: it moves 2px per frame, so on a 120Hz screen it runs twice as fast as on a 60Hz one. Base movement on time, not on frames.
Frame-rate independent animation
Use the timestamp to measure how much time passed since the last frame, then move by speed × time. The animation now takes the same time on every device, even if some frames are dropped.
const speed = 200; // pixels per second
let x = 0;
let last = null;
function frame(now) {
if (last !== null) {
const dt = (now - last) / 1000; // seconds since the previous frame
x += speed * dt;
}
last = now;
box.style.transform = `translateX(${x}px)`;
if (x < 300) requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
Animate over a fixed duration
For “go from A to B in 500ms” animations, compute progress from 0 to 1 and apply an easing function. This is how animation libraries work under the hood.
function animate({ duration, update, easing = (t) => t }) {
const start = performance.now();
requestAnimationFrame(function frame(now) {
const t = Math.min((now - start) / duration, 1); // 0 → 1
update(easing(t));
if (t < 1) requestAnimationFrame(frame);
});
}
const easeOut = (t) => 1 - Math.pow(1 - t, 3);
animate({
duration: 500,
easing: easeOut,
update: (p) => (box.style.opacity = p),
});
Stop an animation with cancelAnimationFrame
Keep the latest ID and pass it to cancelAnimationFrame(). Remember that every frame returns a new ID.
let rafId;
function frame() {
// ...update
rafId = requestAnimationFrame(frame);
}
startButton.onclick = () => (rafId = requestAnimationFrame(frame));
stopButton.onclick = () => cancelAnimationFrame(rafId);
Beyond animations
Throttle scroll and resize handlers
Scroll and resize events can fire many times per frame. If the handler reads layout or updates the page, that’s wasted work. Running the update at most once per frame keeps scrolling smooth. This site’s “On this page” sidebar highlights the current section exactly this way.
let ticking = false;
window.addEventListener('scroll', () => {
if (ticking) return;
ticking = true;
requestAnimationFrame(() => {
updateProgressBar(window.scrollY); // at most once per frame
ticking = false;
});
}, { passive: true });
Wait for the browser to paint (double rAF)
To start a CSS transition on an element you just added, the browser must render its starting state first. Changing the class in the same frame skips the transition. Two nested requestAnimationFrame calls wait until after the first paint.
document.body.append(toast); // starts with opacity: 0
requestAnimationFrame(() => {
requestAnimationFrame(() => {
toast.classList.add('is-visible'); // now the transition runs
});
});
requestAnimationFrame vs setTimeout and setInterval
requestAnimationFrame |
setTimeout / setInterval |
|
|---|---|---|
| Timing | Synced with the screen’s refresh | Fixed delay, out of sync with painting |
| Background tabs | Paused, saving battery and CPU | Keep running (throttled) |
| Smoothness | One update per frame, no stutter | Can skip or double up frames |
| Use for | Anything visual that changes every frame | Delays and work that isn’t drawing |
One thing to remember: because it pauses in background tabs, don’t use it for timers that must keep running, like a countdown. Calculate those from Date.now() instead.
When CSS is the better choice
For simple effects, like hover states, fades, slides or a pulse animation, CSS transitions and animations are less code, and the browser can run them off the main thread. Animating transform and opacity is cheapest in both cases. Use requestAnimationFrame when the motion depends on JavaScript: physics, user input, canvas, or values you calculate every frame.
Either way, respect users who turned on reduced motion in their system settings. The spider in this site’s seasonal Halloween theme runs on a requestAnimationFrame loop and never appears when reduced motion is on.
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
if (!reduceMotion) {
requestAnimationFrame(frame);
}
FAQ
How many times per second does requestAnimationFrame run?
Once per screen refresh: usually 60 times a second, 120 on high-refresh displays, and less when the device is busy. That’s why animations should be based on elapsed time, not on frame count.
Does requestAnimationFrame run in background tabs?
No. Browsers pause it in hidden tabs. The loop continues when the tab becomes visible again; with delta time, cap dt to avoid a big jump.
Is requestAnimationFrame asynchronous?
Yes. It schedules the callback for the next frame and returns immediately. Code after it runs first.
Can I pass arguments to the callback?
Not directly: the browser only passes the timestamp. Use an arrow function: requestAnimationFrame((t) => draw(t, ctx)).
Related: JavaScript tips, CSS pulse animation, web performance and JavaScript array methods.