Learn JavaScript
❯ browser_dom.raf

Smooth Animation with requestAnimationFrame in JavaScript

$concept

requestAnimationFrame schedules callbacks before the browser's next repaint (~60fps, synced to display refresh) — the correct animation driver, replacing setInterval's drift and jank. Each frame receives a high-resolution timestamp for time-based (not frame-based) motion: position = speed * elapsed keeps speed constant across 60Hz and 120Hz displays.

Browsers pause rAF in hidden tabs automatically (free battery savings), and cancelAnimationFrame stops loops on teardown. CSS transitions/animations cover declarative motion; rAF owns programmatic, physics-driven, canvas-rendered movement.

$how it works
1

Sync to repaints

requestAnimationFrame(tick) runs tick right before the next paint — tearing-free by construction.

2

Drive by timestamps

tick(t) receives ms timestamps — move by elapsed time, never per-frame constants, for uniform speed.

3

Loop by re-requesting

Call requestAnimationFrame(tick) inside tick to continue; cancelAnimationFrame(handle) to stop.

4

Hidden tabs pause free

Background throttling stops rAF automatically — animations cost nothing unseen, unlike intervals.

$example
let start;
function tick(t) {
if (!start) start = t;
let p = Math.min((t - start) / 1000, 1);
console.log(Math.round(p * 100) + "%");
if (p < 1) requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
Output
(0% ... 100% across ~1 second, synced to repaints)
1First timestamp anchors start; progress normalizes elapsed over 1000ms.
2Each frame logs rounded percent and re-requests until complete.
3Time-driven motion finishes in one real second on any refresh rate.
$use cases
Canvas games and visualizations updating per repaint
Time-based (not frame-based) motion uniform across displays
Scroll-linked effects driven by repaint-synced reads
Cancelling loops on unmount to free the frame budget

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.