Cancel a Web Animations API effect cleanly
Keep final state in normal styles, handle a rejected finished promise, and clean up when the component leaves.

Cancel an animation without losing the actual interface state. Keep the final state in normal DOM and CSS, treat animation as a temporary overlay, and clean up when the owning component unmounts. If you await an animation’s finished promise, handle cancellation explicitly.
Do not store the result only in the effect
An effect using fill modes can leave a visual state that differs from your ordinary styles. When it is canceled, the element may snap back to an unexpected appearance. Prefer a layout where the correct final state already exists and the animation moves from an offset back to that state.
let active;
async function emphasize(element) {
active?.cancel();
const animation = element.animate(
[{ transform: 'translateY(6px)' }, { transform: 'translateY(0)' }],
{ duration: 220, easing: 'ease-out' }
);
active = animation;
try {
await animation.finished;
} catch (error) {
if (error?.name !== 'AbortError') throw error;
} finally {
if (active === animation) active = undefined;
}
}
function cleanup() { active?.cancel(); }This illustrative browser code needs a reduced-motion gate before starting and cleanup in your component’s lifecycle. The identity check prevents an older animation’s completion handler from clearing a newer reference.
Test cancellation as normal behavior
Cancellation is expected when the user acts quickly, changes a filter, enables reduced motion, or leaves the route. Do not treat every cancellation as an application failure. At the same time, do not swallow unrelated errors that could reveal a real defect.
Use an interruption checklist
- Start an effect, then start it again immediately.
- Remove the component before the effect finishes.
- Enable reduced motion during the effect.
- Confirm the final styles match the latest application state.
- Check the console for unhandled promise rejections.
MDN documents the animation APIs and their lifecycle. Your application still needs a deliberate policy for which state wins. A screenshot after one completed run cannot verify cancellation or cleanup.
References and further reading
The examples and templates above are original. These references support the definitions and documented behavior discussed in the guide.



