Command Palette

Search for a command to run...

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

rAF as a throttle: 50 events, one update

All 50 events arrived before the next frame, so the style was written once, with the latest position. Move your pointer over the grey area: the dot follows, updating at most once per frame.

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?

rAF as a throttle: 50 events, one update

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

events: 50 updates so far: 0
events: 50 updates after the frame: 1