animationend Retires One-Shot Animations

Wait for animationend instead of guessing durations, then remove the element with removeEventListener so CSS drives timing and JS only reacts.

JavascriptResilience

Code

javascriptsnippet
25 lines
// CSS keeps the timing; JS just listens for the moment it finishes.
// .toast { animation: slide-in 180ms ease-out; }
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = 'Deploy started';
document.body.append(toast);

let removed = false;

function retire(event) {
  if (event.target !== toast) return; // child animations bubble up
  removed = true;
  toast.removeEventListener('animationend', retire);
  toast.remove();
}

// Fires when the toast's own animation completes — no setTimeout guesswork.
toast.addEventListener('animationend', retire);

// animationcancel covers the other exit: element hidden or animation aborted.
toast.addEventListener('animationcancel', retire);

setTimeout(() => {
  console.log('toast removed by animationend:', removed);
}, 250);

How the code behaves

One reading: the function retire, doing all the work.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.
  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.
  • The guard event.target !== toast cuts the flow short with an early return when its condition holds.

Using it

Signature: function retire(event)

Output lines are prefixed (toast removed by animationend:), so the effect of each step is right there in the output.

Core statements

toast.addEventListener('animationcancel', retire);
toast.addEventListener('animationend', retire);
setTimeout(() => {
  console.log('toast removed by animationend:', removed);
}, 250);

Interactive Tools for This Topic

FAQ

Does animationend Retires One-Shot Animations run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.