requestAnimationFrame
ELI5 — The Vibe Check
requestAnimationFrame tells the browser 'call my function right before the next screen repaint.' It's the correct way to do smooth animations in JavaScript — synced to 60fps (or whatever the display rate is). Using setInterval for animations is a war crime; use rAF.
Real Talk
requestAnimationFrame is a browser API that schedules a callback to run before the next repaint, typically at 60Hz. It automatically pauses when the tab is hidden, synchronizes with the display refresh rate, and batches DOM reads/writes for optimal rendering performance.
Show Me The Code
let position = 0;
function animate() {
position += 2;
element.style.transform = `translateX(${position}px)`;
if (position < 300) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
When You'll Hear This
"Always use requestAnimationFrame for animations — never setInterval" / "rAF automatically pauses when the tab is hidden, saving CPU and battery"
Related Terms
CSS Animations
CSS animations let you make things move, spin, fade, and bounce using only CSS — no JavaScript needed.
Reflow
A reflow is when the browser recalculates the size and position of everything on the page because you changed one element's layout.
Repaint
A repaint is when the browser redraws pixels because you changed something visual like a color or shadow.
Web Animations API
The Web Animations API lets you do CSS animations and transitions from JavaScript, with full control over playback.