Stockio

requestAnimationFrame Delta Time for Smooth Motion

Use requestAnimationFrame timestamps and delta time for consistent motion, handle background tabs, and stop animation loops cleanly without tying speed to refresh rate.

By Daniel Kim

React Developer ·

On this page

Moving an object two pixels on every frame makes it travel faster on a high-refresh display. A robust animation loop measures elapsed time instead. requestAnimationFrame supplies a timestamp and a scheduling boundary, but your code still needs a clear model for speed, suspension, and cleanup.

Choose time-based motion deliberately

Use a JavaScript frame loop when each frame needs computed behavior, such as a simulation or a path-dependent marker. Prefer CSS or the Web Animations API for straightforward endpoint interpolation. Writing a loop is not inherently more precise or more performant.

Normalize SVG coordinates before using a marker as a moving object. Define speed in units per second, and state whether those units are CSS pixels, SVG user units, or a normalized path distance. Mixing coordinate systems can look like inconsistent timing even when elapsed-time calculations are correct.

Use the svg path scaler to prepare a static visual reference before tuning movement. Export the relevant values into your prototype and keep them fixed during the first timing comparison. This separates appearance decisions from playback behavior and makes changes easier to judge. The tool prepares the artwork or layout; the animation code still owns the timeline.

Define a baseline state that works without animation. Check that its content, controls, and status remain understandable when no intermediate frames are shown. A successful effect connects valid states; it does not hide essential information inside a brief moment that users must catch.

Compute elapsed time from the timestamp

The callback timestamp lets you calculate delta time between frames. Multiply velocity by seconds elapsed rather than by the number of callbacks. Initialize the first frame without movement so the initial timestamp does not produce a large jump.

This example caps a long interval to keep decorative movement from leaping across the viewport after a suspension. That is a design choice, not a physically exact simulation. A game or scientific model may need fixed simulation steps and a separate rendering policy instead of discarding elapsed time.

let requestId;
let previous;
let x = 0;
let active = true;
const speed = 80; // CSS pixels per second
function frame(now) {
if (!active) return;
const dt = previous === undefined ? 0 : Math.min((now - previous) / 1000, .05);
previous = now;
x = (x + speed * dt) % 240;
marker.style.transform = `translateX(${x}px)`;
requestId = requestAnimationFrame(frame);
}
requestId = requestAnimationFrame(frame);
function stop() {
active = false;
cancelAnimationFrame(requestId);
}

Treat this example as a focused implementation pattern, not a complete component. Connect its selectors and lifecycle to your actual application state, and preserve the same outcome when playback is skipped. For terminology and API details, consult MDN’s requestAnimationFrame reference.

Decide what background time means

Browsers commonly throttle or pause animation callbacks in hidden documents. When the tab becomes visible, decide whether the object should resume from where it stopped, catch up to wall-clock time, or restart. Each policy is valid for a different task.

A clock should derive its displayed time from an authoritative clock source rather than accumulating capped frame intervals. A decorative orbit can simply resume. A progress display should reflect actual task progress, not pretend that animation time represents network work. Separate simulation time from real task state.

Use one-variable comparisons during review. Hold the distance constant while changing duration, then hold duration constant while changing the curve. Otherwise a reviewer may prefer the smaller movement rather than the timing change you intended to evaluate. Capture the chosen values beside the prototype so the production version does not rely on visual guesswork.

Related motion and animation guides can help place this effect in a wider motion vocabulary. Consistency should mean similar behavior for similar tasks, not forcing every component to travel the same distance or share one universal duration.

Separate reads from writes

Read geometry before writing style changes for the frame. Repeatedly changing a transform and then asking for layout dimensions can force synchronous work in more complex loops. Cache stable measurements and invalidate them when container size changes.

Use one scheduler for related objects rather than starting an independent loop for every dot. Keep per-frame allocations small and avoid reconstructing large arrays or parsing strings unnecessarily. These choices should follow profiling, but organizing the loop around explicit update and render phases makes later optimization easier.

Review the relevant platform behavior in MDN’s Page Visibility API guide. Where support is incomplete, prefer an immediately usable final state over a complicated fallback that introduces its own timing bugs. Feature detection should gate the enhancement, not access to the underlying task.

Stop loops when nobody needs them

Store the request identifier and cancel it during teardown. Also use an active flag when callbacks can schedule the next frame, preventing a late-running callback from reviving a supposedly stopped loop. Remove visibility and resize listeners alongside the animation controller.

Respect reduced motion by declining to start nonessential loops, not merely hiding their output. An invisible canvas can still consume CPU. Test repeated start and stop actions and confirm that only one active scheduler exists after rapid user input or component remounts.

Run a production-content pass after the isolated demo succeeds. Use long labels, realistic images, narrow containers, and enough neighboring elements to expose overlap. Repeat with keyboard navigation and at least one touch device. A demonstration that works only when the pointer stays still is not a reliable interaction.

Record a short before-and-after trace using the guidance in web.dev’s animation guide. Compare the same interaction with motion enabled and disabled. Look for repeated layout, large paint regions, and delayed input rather than judging performance solely from a smooth recording on a powerful development machine.

Keep a concise acceptance note with the trigger, final state, cancellation policy, and reduced-motion behavior. The broader development collection is useful for implementation context, but the acceptance note should be specific enough that another developer can reproduce this effect without watching a video.

Key takeaways

  • Express velocity in time-based units, not pixels per frame.
  • Define background-tab behavior instead of accepting accidental jumps.
  • Separate geometry reads, state updates, and visual writes.
  • Cancel loops and listeners when their owner is removed.
Featured sponsor

Reach designers & developers at work

Put your product next to the tools people use every day. One sponsor per placement, no tracking pixels.

Become a sponsor

Keep reading

Related articles

More in JavaScript & Frameworks
JavaScript & Frameworks

Web Animations API: Play, Pause, Reverse and Cancel

Control animation playback with Element.animate(), handle finished promises and cancellation, and keep real component state separate from temporary animation effects.

Includes: SVG path scalerSofia MarchettiSofia Marchetti
Typography & Colour

12 Best Free Fonts for Logos and Branding

Explore twelve free fonts that can shape a logo or small-business identity, with practical guidance on each typeface’s personality, legibility, and limits before you use it.

Includes: SVG path scalerArjun RamanArjun Raman
Icons & Illustration

15 Best Free Illustration Libraries

Compare fifteen illustration libraries for landing pages, presentations, and product screens, including editable vectors, character builders, licensing notes, and practical ways to choose a style.

Includes: SVG path scalerMateo FernándezMateo Fernández
Branding & Business

12 Best Logo Inspiration Sites for Designers

Find thoughtful places to study logo design, from curated case studies and working brand systems to searchable galleries, with practical advice for turning references into an original direction.

Includes: SVG path scalerPiotr KowalskiPiotr Kowalski
Dev Tools & AI Coding

How to Optimize SVG Files Programmatically With SVGO

Optimize SVG files through measured cleanup, safe coordinate handling, precision budgets, and visual regression checks that preserve important details.

Includes: SVG path scalerRavi DesaiRavi Desai
Icons & Illustration

SVG Stroke Scaling and Pixel Alignment for Sharp Icons

Fix blurry SVG strokes by understanding centerlines, rendered scale, device pixels, and non-scaling strokes without relying on misleading pixel-grid rules.

Includes: SVG path scalerAiko TanakaAiko Tanaka