requestAnimationFrame
Lesson 36 of 38 in the JavaScript learning path.
How do I animate a progress bar without setInterval?
requestAnimationFrame asks the browser to call you before the next paint.
setInterval fights the refresh rate and keeps firing in a background tab. A frame callback lines up with painting.
Syntax & Parameters
requestAnimationFrame(step);
Example
Interactive preview availableconst bar = document.querySelector("#bar");
let frame = 0;
const start = performance.now();
function step(now) {
const t = Math.min(1, (now - start) / 800);
bar.style.width = (t * 100) + "%";
if (t < 1) {
frame = requestAnimationFrame(step);
}
}
frame = requestAnimationFrame(step);
document.querySelector("#stop").addEventListener("click", () => {
cancelAnimationFrame(frame);
});
Expected Output
The bar grows to full width in about 0.8 seconds. Stop freezes it.
Line-by-Line Walkthrough
- performance.now gives a timestamp.
- step receives the next timestamp.
- t moves from 0 to 1 over 800 milliseconds.
- The bar width follows t.
- Another frame is requested until t reaches 1.
- The stop button cancels the stored id.
- Forgetting cancel leaves the loop running.
- Do not combine this with a second setInterval on the same bar.
Common Pitfalls & Security
Read the limits before you copy this.
- Losing the frame id means you cannot cancel.
- Writing layout in a tight loop without a frame callback causes extra reflow.
- A hidden tab may pause frames. Do not use this as a clock.
- Animating width is less smooth than transform. Width is acceptable for a one-shot bar.
Best Practices & Modern Standards
Store the id and cancel it when the view closes.
Drive motion from a timestamp, not from assuming each call is 16 milliseconds apart.
Real-World Use
A lesson upload shows a determinate bar that fills over a short, known delay and stops cleanly if the student navigates away.
Frequently Asked Questions
How is this different from setInterval?
The browser schedules it with painting and can pause it in a background tab.
What does the callback receive?
A high-resolution timestamp.
How do I stop it?
cancelAnimationFrame with the id from the last request.
Is it a clock?
No. Use it for drawing. Use visibility and timestamps if you need elapsed time.