Custom element animation
Animating DOM properties that CSS cannot handle conveniently.
JS Puzzles · Const
requestAnimationFrame schedules an animation callback for the browser's next suitable animation opportunity. The callback receives elapsed time in milliseconds, and its returned request ID can be used to cancel the scheduled call.
Calling requestAnimationFrame schedules a callback for the browser's next suitable animation-and-repaint opportunity. The callback receives elapsed page-load time in milliseconds; use that timestamp to calculate motion, and call requestAnimationFrame again when another frame is needed.
let requestId = requestAnimationFrame(callback)| Name | Type | Description |
|---|---|---|
callback | function | The function scheduled to run when the browser is ready for the animation opportunity; it receives elapsed page-load time in milliseconds. |
A request identifier that can be passed to cancelAnimationFrame(requestId).
const box = document.querySelector('#box');
let start;
function frame(time) {
start ??= time;
const progress = Math.min((time - start) / 1000, 1);
box.style.transform = `translateX(${progress * 240}px)`;
if (progress < 1) requestAnimationFrame(frame);
}
requestAnimationFrame(frame);Moves the element for one second, using the callback timestamp to calculate progress and scheduling each next frame explicitly.
Animating DOM properties that CSS cannot handle conveniently.
Driving a visual update loop whose progress depends on elapsed time.
Stopping a pending animation when it is no longer needed.
requestAnimationFrame schedules a callback for the nearest time when the browser wants to perform animation, typically while preparing a repaint. This lets the browser coordinate JavaScript animation work with rendering.
Follow-up: How does a continuous animation continue? The callback must schedule the next frame by calling requestAnimationFrame again, usually after updating the element.
The callback receives one argument: the time elapsed since page loading, measured in milliseconds. This value can also be obtained with performance.now(), so it can drive time-based progress rather than assuming a fixed frame interval.
Follow-up: Why use the supplied time? Frame timing depends on the browser, so elapsed time keeps motion consistent when frame intervals vary.
The function returns a request ID. Pass that ID to cancelAnimationFrame(requestId) to cancel the scheduled callback before it runs.
Follow-up: When is this useful? It allows an animation to stop cleanly when its target is removed, hidden, or no longer relevant.
cancelAnimationFrameperformance.nowCSS animations