Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.7 — requestAnimationFrame and Smooth Animation
JavaScript · Example 2 of 3

Per-frame steps vs time-based steps on two screens

Per-frame movement depends on the screen and on dropped frames. Time-based movement covers the same distance in the same time everywhere.

requestAnimationFrame(callback) runs your code right before the browser draws the next frame, in step with the screen; animate by computing each frame from the elapsed time (not by counting frames), change only cheap properties like transform and opacity, and stop with cancelAnimationFrame.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write fadeIn(el, duration) that animates opacity from 0 to 1 with rAF and logs faded when done.

02

Write a countUp(el, to, duration) that animates a number in el.textContent from 0 to to with whole numbers, ending exactly on to.

Explain it without notes

01

What does requestAnimationFrame do, and why is it better than setInterval for animation?

02

Why should animations be based on elapsed time rather than frame count?

03

Which CSS properties are cheapest to animate, and why?

04

How can rAF be used to throttle high-frequency events?

Per-frame steps vs time-based steps on two screens

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

60 Hz: per-frame moved 120px, time-based moved 200px
120 Hz: per-frame moved 240px, time-based moved 200px
30 Hz: per-frame moved 60px, time-based moved 200px