What is requestAnimationFrame used for?
IntermediateBrowser and web interview questionBy UIRound, updated 17 November 2026
Short answer
requestAnimationFrame(callback) asks the browser to run your function once, just before it paints the next frame. It is used for JavaScript animations, for batching visual updates such as a scroll progress bar, and for throttling work to one run per frame. Because it follows the display's refresh rate and pauses in background tabs, it is smoother and cheaper than animating with setTimeout or setInterval.
When the callback runs
The browser repeatedly runs a task, then the microtasks queued by it, and, when it is time for a new frame, the rendering steps: animation frame callbacks, then style, layout and paint. Your callback runs at the start of those rendering steps, so any DOM or style changes it makes appear in the very frame that is about to be painted. On a 60 Hz screen that is about every 16.7 ms; on a 120 Hz screen about every 8.3 ms. The event loop guide shows where this sits among tasks and microtasks.
The callback runs once. To animate, it requests the next frame itself:
const box = document.querySelector(".box");
const duration = 600; // ms
const distance = 300; // px
let start;
function step(now) {
start ??= now;
const progress = Math.min((now - start) / duration, 1);
const eased = 1 - (1 - progress) ** 3; // ease-out cubic
box.style.transform = `translateX(${eased * distance}px)`;
if (progress < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);Why not setTimeout?
setTimeout(fn, 16) |
requestAnimationFrame(fn) |
|
|---|---|---|
| Timing | After at least 16 ms, whenever the task queue reaches it | Right before the next paint |
| Matches the screen | No; drifts against 60, 90, 120 or 144 Hz | Yes, follows the refresh rate |
| Missed or doubled frames | Common: two updates in one frame or none in another | One call per frame |
| Background tabs | Throttled, but still runs | Paused in hidden tabs and hidden iframes in most browsers |
| Timestamp argument | None | The frame's start time |
A timer is not tied to frames, so some frames get two position changes and some get none, which shows as jank. It also keeps running and using battery when nobody can see the page.
The timestamp and frame-rate-independent animation
The callback receives a DOMHighResTimeStamp, in milliseconds on the same clock as performance.now(). All callbacks in the same frame get the same value. Base movement on elapsed time, as in the example above, and never on the number of frames. If you write x += 5 per frame, the box moves twice as fast on a 120 Hz screen as on a 60 Hz one, and slows down whenever frames are dropped. With elapsed time, it covers the same distance in the same time on every device.
Cancelling
requestAnimationFrame returns an id. Pass it to cancelAnimationFrame to stop a pending callback, for example when a component unmounts or the user starts a new animation:
let frameId = 0;
function startLoop() {
const tick = (now) => {
render(now);
frameId = requestAnimationFrame(tick);
};
frameId = requestAnimationFrame(tick);
}
function stopLoop() {
cancelAnimationFrame(frameId);
}In React, call cancelAnimationFrame in the effect cleanup, or a loop keeps running against an unmounted component.
Background tabs
Browsers stop calling animation frame callbacks for hidden tabs. That saves CPU and battery, but it means elapsed time can jump by minutes when the tab returns. Clamp the delta (Math.min(now - last, 100)) in game loops and physics, and do not use requestAnimationFrame for anything that must keep running, such as a countdown. For timing like that, compute from Date.now() or performance.now() against a fixed start time and use the frame only to redraw.
Batching reads and writes to avoid layout thrashing
Reading layout (offsetHeight, getBoundingClientRect()) after writing styles forces the browser to run layout immediately. Doing that in a loop, read, write, read, write, is layout thrashing; see reflow vs repaint. A common fix is to read in your event handler and defer the writes to the next frame:
let scheduled = false;
window.addEventListener("scroll", () => {
if (scheduled) return;
scheduled = true;
requestAnimationFrame(() => {
scheduled = false;
const max = document.documentElement.scrollHeight - innerHeight;
const ratio = max > 0 ? scrollY / max : 0; // reads first
bar.style.transform = `scaleX(${ratio})`; // then one write
});
}, { passive: true });The scheduled flag also throttles the handler to one update per frame, however many scroll events fire. Inside a frame callback, do all reads first and all writes after, so layout runs once.
When you do not need it
For simple transitions, CSS transitions, CSS animations or the Web Animations API (element.animate()) are better. They can run transform and opacity changes on the compositor thread, so they stay smooth even when the main thread is busy. Use requestAnimationFrame when each frame's values depend on JavaScript: physics, drag following the pointer, canvas drawing, or syncing with scroll. To show content when it enters the viewport, use IntersectionObserver rather than measuring in a frame loop. Respect prefers-reduced-motion in both cases.
Practise it
Build the animation above in Animate an element to the right with requestAnimationFrame, then write the throttle in Implement rafThrottle. Batch DOM reads and writes to fix layout thrashing, Build a scroll progress bar and Build a stopwatch with laps that never drifts cover the other uses.
Common follow-up questions
Does requestAnimationFrame guarantee 60 frames per second?
No. It runs once per frame the browser produces. If your callback or other work takes longer than the frame budget, frames are skipped and the callback simply runs less often. That is why animations must use elapsed time.
What happens if I call requestAnimationFrame inside its own callback?
The new callback is queued for the next frame, not the current one. That is what makes the recursive loop work without freezing the page.
What is the "double rAF" trick?
Calling requestAnimationFrame inside another requestAnimationFrame callback runs code after one frame has been painted. It is used to make sure a starting style has been rendered before changing it, so a CSS transition plays. Reading layout, such as offsetWidth, between the two style changes is the other common way to do the same.
Is requestAnimationFrame a macrotask or a microtask?
Neither. It is part of the rendering steps of the event loop, which happen between tasks when the browser decides to render.
Mistakes to avoid
Moving things by a fixed amount per frame instead of by elapsed time
Forgetting
cancelAnimationFramewhen a component unmounts or an animation restartsUsing
requestAnimationFramefor timers that must run in background tabsReading and writing layout alternately inside the callback
Animating
toporleftwhentransformwould avoid layoutUsing a JavaScript loop for an animation CSS could do
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Animate an element to the right over a duration with requestAnimationFrame, without CSS transitionsEasy20 min
- Implement
rafThrottle(): run at most once per animation frame, with cancel and flushMedium30 min - Batch DOM reads and writes to fix layout thrashingMedium35 min
- Build a scroll progress bar: one update per frame, a transform-based fill and progressbar semanticsEasy20 min
- Build a stopwatch with laps that never driftsEasy30 min