Challenge - Timers and animation
Build a smooth progress bar with setInterval and requestAnimationFrame.
Progress bar animation
In this challenge you will build a smooth progress bar. The bar's value increases step by step from zero to one hundred.
You use requestAnimationFrame for this. On each frame you increase the bar's value property a little. The function calls itself again to form a loop.
When it reaches one hundred you stop the loop with cancelAnimationFrame. Otherwise the animation runs forever.
Stopping the animation
Each call to requestAnimationFrame returns a frame id. You store this id in a variable; you need it to stop later.
To stop the animation you call cancelAnimationFrame(id). The id is the value returned by requestAnimationFrame.
If you do not store the id you cannot stop it; the animation keeps running in the background and wastes memory. Always stop as soon as the target is reached.
Exercise Write the startProgress function
Write the startProgress(bar) function. Inside it define a function animate: on each frame increase bar.value by 2. When bar.value >= 100 call cancelAnimationFrame(frameId) and return. Otherwise request the next frame with frameId = requestAnimationFrame(animate). Finally declare frameId and start the first frame.
Show example solution
set bar.value = bar.value + 2, add if (bar.value >= 100) { cancelAnimationFrame(frameId); return; }, otherwise call frameId = requestAnimationFrame(animate). Finally start with frameId = requestAnimationFrame(animate).
Example solution:
function startProgress(bar) {
let frameId;
function animate() {
bar.value = bar.value + 2;
if (bar.value >= 100) {
cancelAnimationFrame(frameId);
return;
}
frameId = requestAnimationFrame(animate);
}
frameId = requestAnimationFrame(animate);
}
Test yourself
-
Start the animation frame
let frameId = ____;Show answer
let frameId = requestAnimationFrame(animate); -
When is requestAnimationFrame preferred?
- For a one-time delay
- For work that repeats at a fixed interval
- For text formatting
- For animations drawn to the screen
Show answer
For animations drawn to the screen — Correct. rAF syncs with the browser's paint loop and gives smooth animation.