Smooth Animation with requestAnimationFrame in JavaScript
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.
Sync to repaints
requestAnimationFrame(tick) runs tick right before the next paint — tearing-free by construction.
Drive by timestamps
tick(t) receives ms timestamps — move by elapsed time, never per-frame constants, for uniform speed.
Loop by re-requesting
Call requestAnimationFrame(tick) inside tick to continue; cancelAnimationFrame(handle) to stop.
Hidden tabs pause free
Background throttling stops rAF automatically — animations cost nothing unseen, unlike intervals.
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);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.