Stockio

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.

By Sofia Marchetti

JavaScript Engineer ·

On this page

The Web Animations API is useful when playback itself is part of the interaction. A demonstration may need pause and resume controls, or a reversible panel may need an explicit animation handle. The API is less useful when a simple CSS transition already expresses the whole state change.

Define who owns playback and state

Choose one controller for each effect. CSS classes, an animation library, and a native Animation object should not all write the same transform without a deliberate composition plan. Put independent motions on separate wrappers when their ownership differs.

For a moving SVG marker, normalize its artwork coordinates before tuning travel. A path scaled into a consistent coordinate space is easier to compare across sizes. Keep application state outside the Animation object: paused, open, selected, and saved describe different concerns and should not be inferred from a single playback timestamp.

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.

Create and retain one animation handle

Element.animate returns an Animation object immediately. Retain that handle rather than creating another effect every time someone presses play. The example creates a simple one-way demonstration and pauses it before interaction. Wire buttons to its methods through ordinary event listeners.

The fill option retains the effect visually after its active interval, but it does not make the final transform part of the element's underlying style. That distinction matters when the effect is canceled or replaced. Choose a final-state policy before building more controls.

const marker = document.querySelector('.marker');
const motion = marker.animate(
[{ transform: 'translateX(0)' }, { transform: 'translateX(120px)' }],
{ duration: 450, easing: 'ease-out', fill: 'both' }
);
motion.pause();
function playMarker() {
motion.play();
motion.finished.catch(error => {
  if (error.name !== 'AbortError') console.error(error);
});
}
function reverseMarker() { motion.reverse(); }
function stopMarker() { motion.cancel(); }

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 Web Animations API guide.

Understand pause, reverse, and cancel

Pause preserves the current playback position. Play resumes or starts playback according to the object's state. Reverse changes playback direction and can produce useful continuity when the user changes their mind. Cancel removes the animation's effect and resets its playback state; it is not equivalent to pause.

Test reversing at the beginning and at the end, not only midway through. Decide whether a finished animation should replay from the start or remain complete until explicitly reset. A UI with ambiguous replay behavior can feel broken even though each method follows the specification.

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.

Handle promises without swallowing state errors

The finished promise resolves when playback finishes, but cancellation rejects it. Catch expected cancellation so removing a component does not produce an unhandled rejection. Do not interpret every rejection as a reason to repeat the application action that originally triggered movement.

If the end position belongs to persistent component state, apply that state explicitly and then remove the temporary effect. commitStyles can help in suitable cases, but understand its support and inline-style implications. Avoid accumulating stale transforms that conflict with responsive styles or future CSS changes.

Review the relevant platform behavior in MDN’s Animation reference. 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.

Clean up on removal and preference changes

Cancel active effects during component teardown and release references to removed elements. Listen for reduced-motion preference changes when a long-running animation is active. In the reduced path, show the correct result immediately rather than pausing at an arbitrary halfway position.

Use race tests: press reverse twice, cancel while awaiting completion, remove the target, and start a newer request before an older one finishes. Guard completion callbacks with a current-operation identity when necessary so an old effect cannot overwrite the newest intended state.

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

  • Use retained handles when explicit playback control is needed.
  • Distinguish cancellation from pausing and completion.
  • Keep persistent component state outside animation fill behavior.
  • Clean up effects and ignore stale completion callbacks.
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

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.

Includes: SVG path scalerDaniel KimDaniel Kim
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