requestAnimationFrame & Smooth Animations0%

requestAnimationFrame & Smooth Animations

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

requestAnimationFrame & Smooth Animations in Modern JavaScript

Creating fluid visual animations in web applications requires synchronizing JavaScript execution with the display hardware's vertical synchronization (V-Sync). Using setInterval or setTimeout for animations causes frame drops, stuttering, and wasted CPU cycles. requestAnimationFrame() is the browser's native API for high-performance visual animations.


1. Why setTimeout & setInterval Fail at Animations

Most computer and mobile displays refresh at 60Hz (once every 16.67ms) or 120Hz (once every 8.33ms).

Output
Display V-Sync (Every 16.67ms):
│ │ │ │
▼ ▼ ▼ ▼
 
setTimeout(fn, 16) (Misaligned with Display Refresh!):
● ● ● ●
(Result: Frames are dropped or drawn twice, causing noticeable stutter / jank!)

Flaws of Timer-Based Animations:

  1. 1
    Misaligned with Hardware V-Sync: Timers fire independently of screen refresh cycles.
  2. 2
    Continues in Background Tabs: setInterval keeps running even when the user switches tabs, draining laptop battery and mobile CPU!
  3. 3
    Timer Throttling: Browsers throttle setTimeout to 1,000ms in inactive tabs.

2. The requestAnimationFrame Mechanics

window.requestAnimationFrame(callback):

  1. 1
    Fires immediately before the browser's next screen repaint, perfectly in sync with V-Sync.
  2. 2
    Automatically pauses when the browser tab is minimized or inactive, conserving battery.
  3. 3
    Automatically passes a high-resolution DOMHighResTimeStamp (performance.now()) to the callback.
JavaScript
let startTime = null;
const box = document.querySelector('#animated-box');
const DURATION = 1500; // 1.5 seconds
 
function animate(currentTime) {
if (!startTime) startTime = currentTime;
const elapsed = currentTime - startTime;
 
// Calculate normalized progress (0.0 to 1.0)
const progress = Math.min(elapsed / DURATION, 1);
 
// Easing function (Ease-out cubic)
const easeOut = 1 - Math.pow(1 - progress, 3);
 
// Translate element using GPU transform
const x = easeOut * 400; // Move 400px
box.style.transform = `translate3d(${x}px, 0, 0)`;
 
// Continue loop until complete
if (progress < 1) {
requestAnimationFrame(animate); // Schedule next frame
} else {
console.log('Animation completed at 60/120 FPS!');
}
}
 
// Start animation loop
requestAnimationFrame(animate);

3. Canceling Animations: cancelAnimationFrame()

To stop an in-flight animation loop (e.g. on user click, modal close, or component unmount):

JavaScript
let animationId = null;
 
function startLoop() {
animationId = requestAnimationFrame(gameLoop);
}
 
function stopLoop() {
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null;
}
}

4. Physics Animation Loop Pattern (Delta Time)

To ensure game physics and animations run at the exact same speed on 60Hz, 120Hz, and 144Hz monitors, always calculate Delta Time ($\Delta t$):

JavaScript
let lastFrameTime = performance.now();
let playerX = 0;
const SPEED = 200; // 200 pixels per second
 
function gameLoop(now) {
const dt = (now - lastFrameTime) / 1000; // Delta time in seconds
lastFrameTime = now;
 
// Position updates based on real elapsed time, NOT frame rate!
playerX += SPEED * dt;
playerElement.style.transform = `translate3d(${playerX}px, 0, 0)`;
 
requestAnimationFrame(gameLoop);
}

Interactive Quiz

Practice Quiz

Question 1
What is the primary advantage of requestAnimationFrame over setTimeout(fn, 16)?
Question 2
What parameter is automatically provided by the browser to the requestAnimationFrame callback function?
Question 3
How do you cancel an animation loop initiated by requestAnimationFrame?
Question 4
Why is "Delta Time" (elapsed time between frames) used in professional animation and gaming loops?
Question 5
What happens to requestAnimationFrame loops when the user switches to a different browser tab?
Next Lesson

Memory Management & Garbage Collection

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext