Start · Sprachen · JavaScript · Referenz · Animation.cancel()

Animation.cancel()

Methode

Bricht die Wiedergabe einer <code>Animation</code> ab, entfernt alle ihre Keyframe-Effekte und setzt <code>currentTime</code> und <code>startTime</code> auf <code>null</code>.

seit JavaScript Baseline: alle modernen Browser (seit 2020) Kategorie: webapi

Signatur

Animation.prototype.cancel()

Beschreibung

Die Methode cancel() der Schnittstelle Animation aus der Web Animations API bricht eine laufende, pausierte oder beendete Animation ab. Alle von ihr verursachten KeyframeEffects werden sofort entfernt, sodass das Element wieder so dargestellt wird, als hätte die Animation nie stattgefunden. Anschließend wechselt playState zu "idle", und sowohl currentTime als auch startTime werden auf null gesetzt.

Einsatzfälle sind z. B. das Abbrechen einer Animation, wenn der Nutzer eine Aktion abbricht, das Zurücksetzen eines Elements vor dem Start einer neuen Animation oder das Aufräumen von Animationen mit fill: "forwards", deren Endzustand sonst dauerhaft erhalten bliebe.

Durch den Aufruf wird das Promise animation.finished mit einem DOMException vom Typ AbortError abgelehnt, und es wird ein cancel-Event ausgelöst (abfangbar über addEventListener("cancel", …) oder oncancel). Für das finished-Promise wird danach ein neues Promise angelegt. Ein späterer Aufruf von play() startet die Animation wieder von vorn.

Beispiele

Animation per Button abbrechen

const box = document.querySelector('.box');
const animation = box.animate(
  [{ transform: 'translateX(0)' }, { transform: 'translateX(300px)' }],
  { duration: 3000, fill: 'forwards' }
);

document.querySelector('#stop').addEventListener('click', () => {
  animation.cancel();
  console.log(animation.playState, animation.currentTime);
});
idle null

Abgelehntes finished-Promise sauber behandeln

const el = document.querySelector('.toast');
const anim = el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 2000 });

const fadeOut = async () => {
  try {
    await anim.finished;
    el.remove();
  } catch (err) {
    // AbortError nach cancel()
    console.log('Abgebrochen:', err.name);
  }
};

fadeOut();
// Nutzer fährt mit der Maus über den Toast -> Ausblenden abbrechen
el.addEventListener('mouseenter', () => anim.cancel(), { once: true });
Abgebrochen: AbortError

Alle Animationen eines Elements zurücksetzen

const card = document.querySelector('.card');

const resetAnimations = (element) => {
  element.getAnimations().forEach((a) => a.cancel());
};

card.animate([{ scale: 1 }, { scale: 1.2 }], { duration: 500, fill: 'forwards' });
resetAnimations(card);
console.log(card.getAnimations().length);

cancel-Event über oncancel auswerten

const anim = document.body.animate(
  [{ backgroundColor: 'white' }, { backgroundColor: 'gold' }],
  { duration: 1000 }
);

anim.oncancel = (event) => {
  console.log('cancel-Event, timelineTime:', event.timelineTime);
};

anim.cancel();
cancel-Event, timelineTime: null

// Wichtig · Fallstricke

  • Unbehandelte Promise-Ablehnung: Wer auf animation.finished wartet, ohne catch zu verwenden, bekommt nach cancel() einen AbortError als „Uncaught (in promise)“ in der Konsole.
  • Kein Endzustand: Anders als finish() springt cancel() nicht zum Ende, sondern entfernt alle Effekte – das Element springt sichtbar in seinen Ausgangszustand zurück. Soll der Endzustand erhalten bleiben, vorher commitStyles() aufrufen oder finish() verwenden.
  • Bei CSS-Animationen und -Transitions (CSSAnimation/CSSTransition) wirkt cancel() ebenfalls, die CSS-Regel kann die Animation jedoch später erneut starten, etwa wenn sich animation-name ändert.
  • Der Aufruf auf einer bereits im Zustand "idle" befindlichen Animation hat keine Wirkung und löst kein cancel-Event aus.
  • Kompatibilität: in allen modernen Browsern (Chrome, Edge, Firefox, Safari 13.1+) verfügbar; nicht im Internet Explorer.