requestAnimationFrame
Learn the requestAnimationFrame loop for smooth animations.
Smooth animation with requestAnimationFrame
requestAnimationFrame calls a function right before the next repaint. This is the right way to build smooth animations; the browser calls it once per frame.
function animate() {
console.log('Frame');
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);To keep the animation going, you call requestAnimationFrame again from inside the callback. This way the function runs again on each frame. This recursive structure follows the browser's drawing rhythm, unlike setInterval.
Stopping with cancelAnimationFrame
To stop an animation you use cancelAnimationFrame(id). requestAnimationFrame returns an id; you store it and pass it to cancelAnimationFrame when you want to stop.
let id = requestAnimationFrame(animate);
cancelAnimationFrame(id);Just like clearInterval, cancelAnimationFrame cancels a frame that has not fired yet. It is used for cleanup when the animation is no longer needed; otherwise extra frames keep being drawn.
Exercise Move the box to the right
Move a .box element to the right with requestAnimationFrame. Each frame, increase left by 2 and assign it to box.style.left with 'px'.
Show example solution
const box = document.querySelector('.box');
let left = 0;
function animate() {
left = left + 2;
box.style.left = left + 'px';
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Test yourself
-
Which API is better for animation?
- setInterval every 16 ms
- setTimeout chain
- console.log loop
- requestAnimationFrame
Show answer
requestAnimationFrame — Correct! requestAnimationFrame follows the browser's frame rhythm, so animations run smoothest.
-
Complete the requestAnimationFrame call
function animate() { console.log('Frame'); ____(animate); } requestAnimationFrame(animate);Show answer
function animate() { console.log('Frame'); requestAnimationFrame(animate); } requestAnimationFrame(animate); -
Match the animation concepts
- requestAnimationFrame
- calls on the next frame
- cancelAnimationFrame
- cancels a frame
- animate
- function run each frame
- id
- the frame's identity