CKTIS / JavaScript
WAAPI: keyframe arrays and timing options
Pass a keyframe array to `Element.animate()` and use a separate options object to set how long each iteration lasts, how it progresses, and how many times it runs.
Version: Current web platform; runtime support varies
Syntax
element.animate(keyframes, { duration, easing, iterations })
element.animate(keyframes, duration)element.animate(keyframes, options) creates and plays an animation on a DOM element and returns the Animation object. The method and its timing options belong to the Web Animations API (WAAPI), not to ECMAScript 2024 or any other ECMAScript edition. Availability depends on the runtime.
In a keyframe array, each object gives values for animatable CSS properties such as opacity at one point in an iteration. An offset places that point between 0 and 1, inclusive. Explicit offsets must be in nondecreasing order. Missing offsets are spaced evenly: three keyframes with no offsets get 0, 0.5, and 1. A single object with property value arrays, such as { opacity: [0, 1] }, is a separate supported format.
In the options, numeric duration is the length of one iteration in milliseconds. Passing a number as the second argument is shorthand for setting only duration. iterations is the total iteration count: it defaults to 1, 2.5 means two full iterations and half of a third, and numeric Infinity sets no finite iteration limit. With a positive finite duration and finite iterations, active duration is duration * iterations, excluding delays.
The options-level easing is a CSS easing function written as a string and defaults to "linear". It changes how progress advances across each whole iteration, not how long that iteration lasts. An easing on a keyframe applies from that keyframe to the next; the two settings can work together.
Examples
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>WAAPI keyframes and timing</title>
<script>
(() => {
const element = document.createElement("div");
const keyframes = [
{ opacity: 0 },
{ opacity: 1, easing: "ease-in" },
{ opacity: 0 },
];
const animation = element.animate(keyframes, {
duration: 600,
easing: "ease-in-out",
iterations: 2.5,
});
const effect = animation.effect;
const { duration, easing, iterations, activeDuration } = effect.getComputedTiming();
const offsets = effect.getKeyframes().map(frame => frame.computedOffset);
console.log(`Offsets: ${offsets.join(", ")}`);
console.log(`${duration} ms × ${iterations} = ${activeDuration} ms; easing: ${easing}`);
animation.cancel();
})();
</script>
</html>Result
Offsets: 0, 0.5, 1 600 ms × 2.5 = 1500 ms; easing: ease-in-out
Save the example as an HTML file, open it in a browser that supports WAAPI, and check the developer console. The element is not added to the page: the example logs computed offsets and timing without waiting, then cancels the animation.
Related lessons
- JavaScript · Lesson 29 · Intermediate · Version: 3