1 Basic Web Animations API Syntax & Simple Duration

The basic syntax is element.animate(keyframes, options). In its simplest form, options can be a single duration number (in milliseconds). Unlike CSS3 animations which default to ease, Web Animations API defaults to linear timing when duration alone is specified.

Code: JavaScript element.animate(keyframes, duration)
linear-fade.js
const simpleFadeBox = document.getElementById('simpleFadeBox');

// 3000ms fade-in with default linear timing
const fadeAnimation = simpleFadeBox.animate([
  { opacity: 0 },
  { opacity: 1 }
], 3000);
Result: Interactive Showcase Live linear fade demonstration
Fade In Box
(3000ms)
State: Idle

2 Keyframes with Offset, Steps Easing & Options Object

Detailed options are passed as an object matching CSS3 animation-* properties. The offset property corresponds to CSS @keyframes percentages (e.g. offset: 0.4 is 40%). Notice the red circle appears rapidly in the first 40% of the timeline and fades over the remaining 60%, stepping through discrete frames with steps(8, end) and looping with iterations: Infinity.

Code: JavaScript The Iconic Stepped Fade Demo
stepped-circle.js
const circleElement = document.getElementById('steppedRedCircle');

const steppedAnimation = circleElement.animate([
  { opacity: 0 },
  { opacity: 1, offset: 0.4 }, // 40% progress mark in CSS
  { opacity: 0 }
], {
  duration: 3000,
  delay: 0,
  fill: 'forwards',
  easing: 'steps(8, end)',
  iterations: Infinity // Note uppercase 'Infinity' in JS vs CSS 'infinite'
});
Result: Interactive Showcase Discrete 8-step flashing red circle
steps(8) offset: 0.4
Running (steps: 8, loop: Infinity)

3 Web Animations API Playback Control Methods

The Animation object returned by element.animate() provides imperative playback methods: play(), pause(), reverse(), finish(), and cancel().

Code: JavaScript Imperative Playback Control
playback-methods.js
const controlBox = document.getElementById('controlMotionBox');

const myAnimation = controlBox.animate([
  { transform: 'translateX(0px) rotate(0deg)', backgroundColor: '#3b82f6' },
  { transform: 'translateX(240px) rotate(180deg)', backgroundColor: '#ec4899' }
], {
  duration: 2500,
  iterations: Infinity,
  direction: 'alternate',
  easing: 'ease-in-out'
});

// Interactive controls
btnPlay.onclick = () => myAnimation.play();
btnPause.onclick = () => myAnimation.pause();
btnReverse.onclick = () => myAnimation.reverse();
btnFinish.onclick = () => myAnimation.finish();
btnCancel.onclick = () => myAnimation.cancel();
Result: Interactive Showcase Real-time animation state manipulation
WAAPI
playState: running

4 Smooth Speed Transitions with updatePlaybackRate()

updatePlaybackRate() sets the animation speed after synchronizing playback positions. Unlike directly setting the playbackRate property, updatePlaybackRate() prevents sudden visual jumps/stutters when changing velocity or reversing direction mid-flight.

Code: JavaScript Dynamic Playback Rate Scaling
playback-rate.js
const spinner = document.getElementById('speedSpinner');

const rotateAnim = spinner.animate([
  { transform: 'rotate(0deg)' },
  { transform: 'rotate(360deg)' }
], {
  duration: 2000,
  iterations: Infinity,
  easing: 'linear'
});

function setSpeed(rate) {
  if (typeof rotateAnim.updatePlaybackRate === 'function') {
    rotateAnim.updatePlaybackRate(rate);
  } else {
    rotateAnim.playbackRate = rate;
  }
}
Result: Interactive Showcase Seamless variable-speed rotation gauge
1.00x

5 Event Interfaces & Promises (onfinish, oncancel, finished)

Web Animations API provides callback events (onfinish, oncancel) and Promise interfaces (animation.finished, animation.ready). Promises resolve cleanly when the animation reaches completion, making async sequencing straightforward.

Code: JavaScript Lifecycle Callbacks & Promises
events-promises.js
const target = document.getElementById('eventTarget');
let anim = null;

function runAnimation() {
  anim = target.animate([
    { transform: 'scale(1) translateY(0)', opacity: 1 },
    { transform: 'scale(1.25) translateY(-25px)', opacity: 0.2 }
  ], {
    duration: 1800,
    fill: 'forwards',
    easing: 'ease-out'
  });

  // Event callbacks
  anim.onfinish = () => log('Event: onfinish triggered');
  anim.oncancel = () => log('Event: oncancel triggered');

  // Promise interface
  anim.finished
    .then(() => log('Promise: anim.finished resolved!'))
    .catch(() => log('Promise: anim.finished rejected/cancelled'));
}

function cancelAnimation() {
  if (anim) anim.cancel();
}
Result: Interactive Showcase Asynchronous event log monitor
Target Element
[System] Console ready. Click "Start" or "Cancel" to inspect events.

6 Key Properties & Real-Time Telemetry HUD

The Animation object exposes live properties including currentTime (elapsed ms), playState ('running', 'paused', etc.), playbackRate, id, and pending. You can also imperatively seek playback by assigning to currentTime.

Code: JavaScript Live Property Inspection & Timeline Seeking
telemetry-properties.js
const telemetryTarget = document.getElementById('telemetryTarget');

const telemetryAnim = telemetryTarget.animate([
  { transform: 'scale(0.85) rotate(0deg)', filter: 'hue-rotate(0deg)' },
  { transform: 'scale(1.2) rotate(180deg)', filter: 'hue-rotate(180deg)' }
], {
  id: 'pulse-telemetry-01',
  duration: 2400,
  iterations: Infinity,
  direction: 'alternate',
  easing: 'ease-in-out'
});

// Read & scrub currentTime live:
// telemetryAnim.currentTime = scrubbedMsValue;
Result: Interactive Showcase Live property HUD & scrub controller
Telemetry Core
id
pulse-telemetry-01
playState
running
currentTime
0 ms
playbackRate
1.0
pending
false

7 Dynamic & Randomized Keyframe Generation

As zhangxinxu noted, the biggest advantage of Web Animations over CSS3 is runtime flexibility. Keyframes, trajectories, scales, and colors can be dynamically calculated in JavaScript at the exact moment of user interaction and cleaned up automatically via onfinish.

Code: JavaScript Procedural Dynamic Keyframe Generator
random-particles.js
function launchParticle(container, originX, originY) {
  const dot = document.createElement('div');
  dot.className = 'burst-dot';
  dot.style.left = originX + 'px';
  dot.style.top = originY + 'px';
  container.appendChild(dot);

  const angle = Math.random() * Math.PI * 2;
  const distance = 60 + Math.random() * 100;
  const destX = Math.cos(angle) * distance;
  const destY = Math.sin(angle) * distance;
  const hue = Math.floor(Math.random() * 360);

  const anim = dot.animate([
    { transform: 'translate(0, 0) scale(1)', opacity: 1, backgroundColor: `hsl(${hue}, 95%, 65%)` },
    { transform: `translate(${destX}px, ${destY}px) scale(0)`, opacity: 0, backgroundColor: `hsl(${hue + 45}, 90%, 50%)` }
  ], {
    duration: 600 + Math.random() * 600,
    easing: 'cubic-bezier(0.1, 0.9, 0.2, 1)',
    fill: 'forwards'
  });

  anim.onfinish = () => dot.remove();
}
Result: Interactive Showcase Click anywhere inside the sandbox to burst dynamic particles
✦ Click or tap anywhere in this area to spawn dynamic animations ✦
Dynamic WAAPI Particles