🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

The Web Animations API: animate(), Timing, Control

Web FoundationsBrowser APIsđŸŸĸ Free Lesson

The Web Animations API: animate(), Timing, Control

CSS animations excel at declarative, always-the-same motion: a hover underline, a spinner, a looping pulse. JavaScript animation with requestAnimationFrame handles everything else but forces you to own interpolation, easing, and the clock yourself. The Web Animations API sits between them: you describe keyframes and timing in JavaScript, the browser interpolates on the compositor thread, and you get a live Animation object back — with currentTime, playbackRate, play, pause, and a finished promise that makes sequencing reliable.

That last part is the API's real payoff. Chaining CSS animations means guessing with transitionend listeners and animation-delay arithmetic. Chaining WAAPI animations is awaiting one promise before starting the next. This lesson covers the animation object, keyframe formats, timing details that are easy to get wrong, and the reduced-motion obligations that come with any programmable motion.

The Animation Object

element.animate takes two arguments: a keyframe array and an options object. What it returns is an Animation instance that stays under your control for its whole lifetime:

MemberTypePurpose
play, pause, cancel, finishMethodsDirect playback control
currentTimeMilliseconds or nullSeek or read position
playbackRateNumberSlow down, speed up, or reverse
playStateStringrunning, paused, finished, idle
finishedPromiseResolves when playback completes
onfinish, oncancelHandlersEvent-style completion hooks

Because the animation starts immediately when animate is called, a common pattern for user-triggered motion is to create it paused, then play on the condition you care about. Canceling returns the element to its unanimated state, which is exactly what you want when a component unmounts mid-flight.

Keyframes: Arrays, Offsets, and Composite Modes

Keyframes may be simple arrays of property objects — the browser distributes them evenly across the duration — or explicit objects carrying an offset between zero and one:

javascript
const panel = document.getElementById('panel');

const entrance = panel.animate(
  [
    { opacity: 0, transform: 'translateY(16px) scale(0.98)', offset: 0 },
    { opacity: 1, transform: 'translateY(0) scale(1)', offset: 0.6 },
    { opacity: 1, transform: 'translateY(0) scale(1)', offset: 1 }
  ],
  {
    duration: 420,
    easing: 'cubic-bezier(0.22, 1, 0.36, 1)',
    fill: 'forwards'
  }
);

Offsets let you front-load easing visually even with a single global easing curve — here the panel arrives at its resting position at sixty percent of the duration and holds. The fill option is the WAAPI equivalent of animation-fill-mode: forwards keeps the final keyframe applied after the animation finishes, which is almost always what you want for an entrance, and both applies the first keyframe before a delay elapses.

Two lesser-known options change how animations stack. composite: add merges keyframes on top of the underlying value instead of replacing it, which lets a highlight animation run over a base transform without knowing what that transform is. composite: accumulate blends transform matrices mathematically. For everyday UI motion, the default replace is correct; reach for the others when composing independently authored effects.

Timing Options Worth Memorizing

javascript
function shake(element) {
  return element.animate(
    [
      { transform: 'translateX(0)' },
      { transform: 'translateX(-6px)' },
      { transform: 'translateX(6px)' },
      { transform: 'translateX(-3px)' },
      { transform: 'translateX(0)' }
    ],
    {
      duration: 320,
      easing: 'ease-in-out',
      iterations: 1,
      direction: 'normal',
      delay: 0
    }
  );
}

document.getElementById('submit').addEventListener('click', (event) => {
  if (!window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
    shake(event.currentTarget);
  }
});

The members you will use most are duration in milliseconds, delay, iterations — where Infinity enables looping — direction, which can be normal, reverse, or alternate, and easing. Easing accepts the same named curves and cubic-bezier functions as CSS, applied across each iteration rather than across the whole animation when direction is alternate. fill accepts none, forwards, backwards, or both; none is the default and the source of the classic "animation snaps back at the end" surprise.

Beyond creation options, the animation object supports live manipulation. Setting currentTime to a millisecond value seeks instantly, which is how scrubber UIs drive timeline previews without starting playback. Negative currentTime lands inside the delay phase. playbackRate of zero is equivalent to pause but preserves the rate for later resumption, and a negative rate plays the animation backwards from its current position — useful for reversing an entrance without re-authoring reversed keyframes. These controls are the reason interactive product tours prefer WAAPI over CSS: the tour's progress bar and the animation's position share one source of truth.

Sequencing With the finished Promise

Every animation exposes a finished promise that resolves on completion and rejects on cancellation. Awaiting it turns sequential motion into linear code:

javascript
async function highlightRow(row) {
  const pulse = row.animate(
    [{ backgroundColor: 'rgba(56, 189, 248, 0)' },
     { backgroundColor: 'rgba(56, 189, 248, 0.35)' }],
    { duration: 180, fill: 'forwards' }
  );
  await pulse.finished;

  const badge = row.querySelector('.badge');
  await badge.animate(
    [{ opacity: 0, transform: 'scale(0.8)' },
     { opacity: 1, transform: 'scale(1)' }],
    { duration: 220, fill: 'forwards', easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)' }
  ).finished;

  const fade = row.animate(
    [{ backgroundColor: 'rgba(56, 189, 248, 0.35)' },
     { backgroundColor: 'rgba(56, 189, 248, 0)' }],
    { duration: 400, fill: 'forwards' }
  );
  return fade.finished;
}

Because the awaits run inside an async function, rapid repeated triggers can interleave — guard by canceling the previous sequence or by checking whether the row is already animating before starting another. For parallel motion, start all the animations first and await Promise.all of their finished promises; awaiting serially there is a common source of staggered-looking bugs.

Scroll-Triggered Motion With IntersectionObserver

Pairing WAAPI with an IntersectionObserver gives declarative-feeling entrance motion with none of the scroll-handler throttling problems:

javascript
const observer = new IntersectionObserver((entries, obs) => {
  for (const entry of entries) {
    if (!entry.isIntersecting) continue;
    entry.target.animate(
      [{ opacity: 0, transform: 'translateY(24px)' },
       { opacity: 1, transform: 'translateY(0)' }],
      { duration: 500, fill: 'forwards', easing: 'ease-out' }
    );
    obs.unobserve(entry.target);
  }
}, { threshold: 0.2 });

document.querySelectorAll('[data-reveal]').forEach((el) => observer.observe(el));

Unobserving after the first intersection keeps the observer cheap and prevents re-triggering when the user scrolls back. If your design wants a replay on re-entry, skip the unobserve — but consider whether repeated motion helps or distracts.

WAAPI Versus CSS Animations Versus rAF

CriteriaWAAPICSS animationsrequestAnimationFrame
Where keyframes liveJavaScriptStylesheetsJavaScript math
Programmatic controlFirst classLimited to eventsTotal
Sequencingfinished promisesdelay arithmeticmanual
Drives many identical itemsPer-element callsOne rule, many elementsPer-element cost
Pauses with tab hiddenYesYesYou must handle it
Best forInteractive, stateful motionDeclarative, repeated chromeCanvas-like custom interpolation

Use CSS when the motion is a pure function of state and markup — a class toggles, the animation runs — and when dozens of elements should share one definition. Use WAAPI when motion depends on data, needs canceling or seeking, or must be sequenced. Keep rAF for cases where you are interpolating values the animation engine does not model, such as canvas drawing.

Respect the Reduced-Motion Preference

Programmable motion carries an obligation. matchMedia with the prefers-reduced-motion query is the gate: when the user asks for reduced motion, either skip decorative animations entirely or replace them with an instant state change or a gentle opacity fade. Check the query at trigger time, not only at load, because users can change the system setting while a page is open. Motion that conveys essential information — a progress bar filling — may stay; motion that only adds flourish must yield.

⚡Animate only compositor-friendly properties

transform and opacity are promoted to the compositor and stay smooth under main-thread pressure. Animating width, height, top, or box-shadow forces layout and paint every frame. Where a size change is required, animate a transform scale or a clipped pseudo-element instead.

Common Mistakes

Leaving fill unset and watching entrance animations snap back

Fix: Pass fill: forwards for one-way motion, or accept the reset deliberately.

Forgetting to cancel animations when a component unmounts

Fix: Keep a reference and call cancel in the cleanup path to avoid detached-element leaks.

Awaiting animations serially when they should run in parallel

Fix: Start all animations first, then await Promise.all of their finished promises.

Animating layout properties on every frame

Fix: Stick to transform and opacity; reach for width only when no transform equivalent exists.

Ignoring prefers-reduced-motion because the animation is subtle

Fix: Gate every decorative animation at trigger time with the media query.

Key Takeaways

  • element.animate returns a controllable Animation object with currentTime, playbackRate, and a finished promise.
  • Explicit keyframe offsets let you shape motion inside a single global easing curve.
  • fill: forwards keeps the end state applied — without it, motion snaps back when playback completes.
  • Sequence with await animation.finished; run parallel motion with Promise.all.
  • IntersectionObserver plus WAAPI handles scroll entrances without scroll-event handlers.
  • Always honor prefers-reduced-motion, and animate transform and opacity for compositor-friendly performance.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement