Schedule visual updates with animation frames
Quick answer
requestAnimationFrame schedules a one-shot callback during a rendering opportunity. Use its timestamp to calculate progress rather than assuming each callback advances the same amount.
How it works
Call requestAnimationFrame(callback) and retain the returned request ID for cancelAnimationFrame. Request another frame inside the callback only if animation continues. Compute elapsed time from timestamps supplied to callbacks. Refresh rates vary; browsers commonly pause callbacks in hidden pages. Frame callbacks are not background timers and do not guarantee exact paint or elapsed intervals. Respect prefers-reduced-motion and avoid essential content depending on animation.
Local examples
Run in a fresh browser document with local synthetic data. Actual ByteMind editor support is unverified.
(async () => {const t=await new Promise(resolve=>requestAnimationFrame(resolve));console.log(typeof t,Number.isFinite(t));})()Expected console output:
number trueThe callback timestamp is numeric and finite; no exact frame time is asserted.
Run in a fresh browser document with local synthetic data. Actual ByteMind editor support is unverified.
(async () => {let ran=false;const id=requestAnimationFrame(()=>ran=true);cancelAnimationFrame(id);await new Promise(resolve=>requestAnimationFrame(resolve));console.log(ran);})()Expected console output:
falseThe canceled callback does not run before the next active frame callback.
Common mistakes
Do not increment a fixed number of pixels per callback to represent a fixed speed across displays. Cancel pending callbacks during teardown.
Practice
Animate a bounded progress value with elapsed timestamp, stop at the endpoint, and provide a reduced-motion alternative.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Schedule visual updates with animation frames — Knowledge Check
Apply the concept and reason about local example output.
How many callbacks does one requestAnimationFrame schedule?
Why use the frame timestamp to compute animation progress?
What does cancelAnimationFrame cancel?
What is the exact console output in Schedule visual updates with animation frames example 1?
(async () => {const t=await new Promise(resolve=>requestAnimationFrame(resolve));console.log(typeof t,Number.isFinite(t));})()What is the exact console output in Schedule visual updates with animation frames example 2?
(async () => {let ran=false;const id=requestAnimationFrame(()=>ran=true);cancelAnimationFrame(id);await new Promise(resolve=>requestAnimationFrame(resolve));console.log(ran);})()