rafTimeline (RequestAnimationFrame)
The controller that runs an animation tree frame by frame, manages its state and controls its playback.
The rafTimeline is the execution engine for any animation you create. It takes a root animation node (like a sequence or parallel block), computes the animation state on every frame of a clock, and notifies subscribers through onUpdate.
Example
import * as a from "@freestylejs/ani-core";
// 1. Define the animation structure.
// TypeScript infers the data shape `G` as { opacity: number, x: number }
const myAnimation = a.sequence([
a.ani({ to: { opacity: 1, x: 0 }, duration: 1 }),
a.ani({ to: { opacity: 1, x: 100 }, duration: 2 }),
]);
// 2. Create a reusable timeline instance from the structure.
const myTimeline = a.rafTimeline(myAnimation);
// 3. Listen for updates to apply the animated values to your UI.
const unsubscribe = myTimeline.onUpdate(({ state, status }) => {
// `state` is strongly typed as { opacity: number, x: number }
console.log(`Opacity: ${state.opacity}, X: ${state.x} (${status})`);
});
// 4. Play the animation from a starting state.
myTimeline.play({ from: { opacity: 0, x: 0 } });
// 5. Release the timeline when it is no longer needed.
// myTimeline.dispose();Usage & Concepts
Overview
The timeline separates the animation definition (the node tree) from its execution and values. When you call play(), it compiles the tree into per-property lanes once, then advances them from the clock.
- Per-frame cost depends on the number of animated properties, not on how many segments the tree has or how many already finished.
- Subscribers of one notification receive the same
stateobject. Treat it as read-only. - One notification per frame.
updateonly computes; bound styles are written andonUpdatelisteners run in the clock's commit phase, after every timeline on the clock has computed. The frame a run ends notifies once, withENDEDand the final value; a frame that wraps a repeat notifies once with the post-wrap value.play(),seek()andreset()notify synchronously. - Errors thrown by an
onUpdatecallback do not affect other callbacks or the timeline. They are rethrown asynchronously (they surface as uncaught errors).
Lifecycle
status is one of four values:
| Status | Meaning | Entered by |
|---|---|---|
IDLE | Nothing is playing and no value exists. | Creation, reset() |
PLAYING | Subscribed to the clock and advancing. | play(), resume() |
PAUSED | Holding its value, not on the clock. | pause(), seek() |
ENDED | Reached the end (after all repeats). Emitted exactly once per run. | Natural end |
pause()only acts onPLAYINGandresume()only acts onPAUSED. In any other status they do nothing.seek(time)clampstimeto[0, duration], pauses aPLAYINGorENDEDtimeline at that time and notifies once. Callresume()to continue from there. Callingseek()before the firstplay()does nothing.reset()returns toIDLE, drops the value (valueisnull) and restores the baseduration. Subscribers receive oneIDLEnotification with an empty state. It takes no arguments.dispose()stops the timeline for good: it leaves the clock, removes everyonUpdatecallback, andplay()/resume()become no-ops. It is idempotent.
Binding styles
bind(target, options?) writes the timeline's value to target.style (an element or any { style }) on every notification, so you do not need an onUpdate callback just to set styles.
import * as a from "@freestylejs/ani-core";
const myTimeline = a.rafTimeline(a.ani({ to: { x: 100 }, duration: 1 }));
const element = document.createElement("div");
const other = document.createElement("div");
const unbind = myTimeline.bind(element)
// optional: decide which declaration a value becomes
myTimeline.bind(other, {
resolver: { x: (v) => ({ key: 'left', value: `${v}px` }) },
})- The value goes through
createStyleSheet;resolveris the mapping from animated values to style declarations. - Writes happen in the commit phase, before the
onUpdatelisteners of the same notification, and only for declarations whose value changed since that binding's previous write. - A timeline that already has a value writes it immediately; otherwise the first write happens at the next notification.
- An invalid
target(not an element or an object with astyleobject) throws aTypeErrorsynchronously. - The returned function unbinds (idempotent) and keeps the written styles.
dispose()drops all bindings. - Positional (array) values cannot be styled: the first write reports a
TypeErrorasynchronously and the binding is dropped. - A write that throws is isolated per binding and rethrown asynchronously.
Validation
Malformed input throws synchronously from play() and leaves the timeline untouched. Nothing can throw later inside the clock.
- A property animated by the tree is missing from
from. - Array and record shapes are mixed (array
towith a recordfrom, or the reverse), or lengths differ. - A record
timinghas no function for an animated property. from,toorvelocitycontain a non-finite number.- A segment duration is negative or not finite.
delayis negative or not finite. keyframesordurationsdo not match the number ofaninodes.
Interrupting a running animation
Calling play() on a PLAYING timeline interrupts it. Pass interrupt: false in the config to ignore the call instead; the returned promise then resolves 'skipped'. play() takes the config only: an extra argument throws a TypeError.
- Velocity carries over. Without
config.velocity, the new run starts from the current velocity, so springs retarget without a visible kink. - Pass
velocity: { x: 0 }(same shape asfrom, partial for records) to start from rest. play()fromIDLE,PAUSEDorENDEDstarts from zero velocity.
Values and velocity
valueis a frozen snapshot that is stable until the next frame. It never aliases thefromobject you passed toplay(). It isnullbefore the firstplay()and afterreset().velocityis the per-property velocity in units per second: the spring's own velocity for atiming.spring, otherwise the finite difference of the last frame. It is zeros unless the status isPLAYING, andnullbefore the first advanced frame.configis the config of the current run, ornull.
Run result
play() returns a Promise<RunResult> that never rejects and resolves exactly once per run, synchronously at the moment the run ends:
| Result | When |
|---|---|
'ended' | The run, repeats included, completed. |
'interrupted' | Another play() replaced it. |
'skipped' | interrupt: false on a PLAYING timeline. |
'reset' | reset() was called. |
'disposed' | dispose() was called, or play() on a disposed timeline. |
An invalid config still throws synchronously before anything changes; no promise is created then. isRafTimeline(value) is a type guard that is true for a timeline and for the facade returned by createTimelineController.
Repeat, delay and time
repeatis the number of additional runs (Infinityfor endless). The frame overshoot at the end of a run is carried into the next one, so repeats do not drift.delayis in seconds (finite and>= 0) and holds the animation before the first frame.- Progress per frame follows the clock's lag smoothing: real elapsed time up to 0.5 s, one ordinary frame after a longer suspension. See clock.
- An animation is considered finished within
1e-9seconds of its end (END_TOLERANCE).
Progress-linked time
drive(progress, config) makes the time follow an external progress value (scroll position, a scrubbed gesture) instead of the clock. It starts a run from config.from (keyframes and durations are honored; repeat, delay and velocity are ignored) and replaces the current run, so a pending play() promise resolves 'interrupted'.
import * as a from "@freestylejs/ani-core";
const hero = document.querySelector<HTMLElement>(".hero")!
const reveal = a.rafTimeline(a.ani({ to: { opacity: 1, translateY: 0 }, duration: 1 }))
reveal.bind(hero)
const stop = reveal.drive(() => Math.min(1, window.scrollY / 400), { from: { opacity: 0, translateY: 40 } })progress()is called once synchronously for the first value (targets written, listeners notified once) and then once per frame in the clock's read phase. The time isclamp(progress(), 0, 1) * duration.- Bound targets are written and listeners notified only in frames where the time changed. The status stays
PLAYINGand the run never ends by itself (reaching1does not emitENDED). velocityis the time-derivative of the values in units per second, and zero after a frame in which the progress did not change.- A non-finite progress keeps the previous time and is reported once, asynchronously.
- Reduced motion does not apply: the user controls the motion.
- The returned function stops driving (idempotent): the timeline leaves the clock and becomes
PAUSEDat the current time, andresume()plays forward from there.play(),seek(),reset()anddispose()stop driving too. - Invalid
config, or aprogressthat is not a function, throws synchronously and changes nothing.
Reduced motion
rafTimeline honors prefers-reduced-motion by default. With the preference on, the policy 'jump' completes every run at once: the value is the end state, bound targets are written, listeners are notified once with ENDED and the promise resolves 'ended'. The clock is not subscribed. The preference is read once at the start of each play().
reducedMotion: { maxDuration }plays a longer run faster instead;durationstill reports the plan's.reducedMotion: 'ignore'keeps the normal behavior, for essential motion.drive()is not affected: the user controls the motion.
import * as a from "@freestylejs/ani-core";
const progress = a.rafTimeline(
a.ani({ to: { width: 100 }, duration: 1 }),
{ reducedMotion: "ignore" }
);See Reduced motion.
Same-property overlap
When several segments animate the same property at overlapping times (parallel, stagger, nested trees), the segment that started most recently produces the value. If two start together, the later one in declaration order wins.
- Each segment's
fromis the property's value at the segment's start time, captured once. It is never a moving target. - Times within 1e-9 s of each other are one instant: sums taken in different orders (a loop's
i * period, a sequence's durations added one by one) leave the same instant a few ulps apart, and the plan stores one value per instant. A zero-length segment applies at its start time, so a time sampled at that instant shows its value.rafTimelineandwaapiTimelinefollow the same rule. - The rule is identical for record and array shapes.
Best Practices
- Do create one timeline per independent animation and reuse the same node tree for many timelines.
- Do call
dispose()for timelines you create when their owner goes away. Bindings dispose only what they create. - Don't create a new timeline inside a render loop. Create it once and store it.
- Don't call
update(dt)yourself outside tests. The clock drives it.
API Reference
Factory
| Name | Type | Description |
|---|---|---|
rootNode | AnimationNode<G> | Root of the animation tree. |
options.clock | AnimationClockInterface | (Optional) Drives the timeline. Defaults to the shared defaultClock. A bare clock in place of the options object throws a TypeError: pass { clock }. |
options.reducedMotion | 'jump' | 'ignore' | { maxDuration: number } | (Optional) Policy while the user prefers reduced motion. Default 'jump'. |
play(config)
| Option | Type | Description |
|---|---|---|
from | AniGroup<G> | Start values. Every animated property must be present. Copied at play(). |
repeat | number | Additional runs. Infinity loops forever. |
delay | number | Seconds to wait before starting (finite and >= 0). |
keyframes | Array<G | 'keep'> | Override each ani node's to. See Dynamic Animations. |
durations | Array<number | 'keep'> | Override each ani node's duration (seconds). |
velocity | Partial<G> | Initial velocity (units per second) that seeds a timing.spring. |
interrupt | boolean | Default true. With false, a PLAYING timeline is left untouched and the promise resolves 'skipped'. |
Members
| Member | Description |
|---|---|
status | 'IDLE' | 'PLAYING' | 'PAUSED' | 'ENDED'. |
duration | Total duration in seconds of the current plan (reflects durations overrides). |
config | The config of the current run, or null. |
value / velocity | Frozen value snapshot and per-property velocity, or null. |
drive(progress, config) | Link the time to an external progress value; returns a stop function. See Progress-linked time. |
pause() / resume() | Pause a PLAYING timeline, resume a PAUSED one. |
seek(time) | Jump to time seconds and pause. |
reset() | Return to IDLE. |
dispose() | Stop for good and release everything. |
disposed | Read-only; true once dispose() ran. |
bind(target, options?) | Write the value to target.style on every notification. Returns an unbind function. |
onUpdate(cb) | Subscribe to { state, status } (commit phase). Returns an unsubscribe function. |
Type Definitions
type TimelineStatus = 'IDLE' | 'PLAYING' | 'PAUSED' | 'ENDED'
type OnUpdateCallback<G extends Groupable> = (current: {
state: AniGroup<G> // shared by all callbacks of one notification
status: TimelineStatus
}) => void
interface RafTimelineConfig<G extends Groupable> {
from: AniGroup<G>
repeat?: number
delay?: number // seconds
keyframes?: Array<G | 'keep'>
durations?: Array<number | 'keep'>
velocity?: Partial<G>
interrupt?: boolean // default true
}
type RunResult = 'ended' | 'interrupted' | 'skipped' | 'reset' | 'disposed'
function rafTimeline<G extends Groupable>(
rootNode: AnimationNode<G>,
options?: {
clock?: AnimationClockInterface
reducedMotion?: 'jump' | 'ignore' | { maxDuration: number }
}
): RafTimeline<G>
function isRafTimeline(value: unknown): value is RafTimeline<Groupable>Related Components
ani- The basic building block for animations controlled by a timeline.clock- What drivesrafTimelineframe by frame.createStates- A state machine of timelines.Dynamic Animations- For creating interactive animations.Large-scale usage- Costs, sharing and ownership rules.