Summary - Timers
Build a countdown timer with setInterval and a simple animation with requestAnimationFrame.
Summary - Timers
In this group you learned four timer APIs. setTimeout runs once, setInterval runs repeatedly. requestAnimationFrame is called frame by frame for animations. You stop all of them with an id.
setTimeout(fn, 1000); // once after 1s
setInterval(fn, 1000); // every 1s
requestAnimationFrame(fn); // next frame
clearInterval(id); // stopStoring ids and cleaning up when needed prevents memory leaks. Let us combine them in two mini tasks.
Exercise Build a countdown from 10
Count down from 10 in a #counter element. With setInterval, decrease seconds by 1 every second, write it to counter.textContent, and stop with clearInterval at 0.
Show example solution
const counter = document.querySelector('#counter');
let seconds = 10;
counter.textContent = seconds;
const id = setInterval(() => {
seconds = seconds - 1;
counter.textContent = seconds;
if (seconds === 0) {
clearInterval(id);
}
}, 1000);
Exercise Fade out an element
Fade out a .fade element with requestAnimationFrame. Each frame, decrease opacity by 0.01 and assign it to fade.style.opacity.
Show example solution
const fade = document.querySelector('.fade');
let opacity = 1;
function fadeOut() {
opacity = opacity - 0.01;
fade.style.opacity = opacity;
requestAnimationFrame(fadeOut);
}
requestAnimationFrame(fadeOut);
Test yourself
-
Which is the best choice to move an element smoothly at 60 fps?
- a recursive loop with requestAnimationFrame
- setInterval every 16 ms
- a setTimeout chain
- a console.log loop
Show answer
a recursive loop with requestAnimationFrame — Correct! requestAnimationFrame follows the browser's frame rhythm and gives the smoothest animation.
-
Match APIs to their use case
- setTimeout
- one delayed call
- setInterval
- repeating call
- requestAnimationFrame
- smooth animation
- clearInterval
- stop a repeating timer