Frontend developer debugging Animation.finished promises while replaying an animation in browser developer tools.

You Replayed the Animation. Which finished Promise Are You Awaiting?

Mon, Nov 30, 2026

A cleanup callback fires almost immediately after an animation is replayed. The element is still parked at the beginning of the second playback interval, yet application state already says the operation completed. Nothing is wrong with Animation.finish(), Animation.play(), or JavaScript Promise scheduling. The application retained the wrong completion handle.

The precise defect is animation finished promise reuse: code captures animation.finished for one playback interval, lets that Promise fulfill, then later reuses the same Animation object while continuing to await the historical Promise. MDN's Animation.finished documentation explains that when an animation leaves its finished state, the finished property can expose a new Promise for the new sequence; the Web Animations specification defines the underlying current-finished-promise replacement algorithm.

Executive summary: an Animation object's identity is not the identity of a playback cycle. A raw Animation.finished Promise belongs to the lifecycle interval for which it was current. Once that Promise fulfills, retaining it is legitimate historical evidence, but it does not become the completion signal for a later replay. The repair is to initiate the state transition for the intended operation, capture the current raw finished handle after that transition, and authorize completion only from that handle, optionally guarded by an application-owned cycle token.

This article specifies a ten-case browser qualification fixture that makes that distinction falsifiable. No browser laboratory was executed during preparation. Every case below is EXPECTED / NOT EXECUTED, with executed=false and observed=null. Browser and operating-system versions have not yet been recorded. The eventual qualification decision therefore remains HOLD until the fixture runs against a frozen runtime tuple and its raw evidence is retained.

1. State which playback completion may authorize the next action

The application contract needs three identities, not one.

First is the Animation object: the JavaScript object whose methods and properties control one native Web Animations player. Second is the playback interval the application currently cares about: for this article, a finite forward interval ending at 1000 milliseconds. Third is the application effect authorized when that interval completes: increment a synthetic completion counter, perform UI cleanup, enable another control, or begin subsequent work.

Those identities can coincide during a simple one-shot animation and diverge as soon as the object is reused.

The tested API is specifically Animation.finished, whose getter returns the animation's current finished Promise. The Web Animations Level 1 document available from W3C is a Working Draft dated June 5, 2023, not a Recommendation and not a 2026 release. Its algorithms describe current ready and finished promises, playing, pausing, finishing, canceling, and updating finished state.

Do not import semantics from another API merely because it also has a property called finished. Refonte's earlier View Transition promise and DOM-state validation investigates ViewTransition lifecycle boundaries. That is a different object model and a different acceptance problem. The present test is about a reusable native Animation.

The completion-ownership rule for this fixture is:

An application operation may be completed only by the raw Animation.finished Promise that was current for the playback interval owned by that operation, plus any independent application-generation check required to reject stale queued work.

The rule deliberately says neither “the animation's Promise” nor “whatever Promise was captured when the component was created.” An animation can outlive a playback interval. A Promise can also remain a perfectly valid settled historical object after the animation has moved into another interval.

play() is not itself a completion Promise. MDN's current Animation.play() reference says it starts, resumes, or restarts an ended animation, and its return value is undefined. Therefore await animation.play() cannot mean “await playback completion.”

That distinction is the integration risk: established browser APIs can be individually correct while application ownership is wrong.

2. Distinguish an animation object from its current finished promise

The browser maintains a current finished Promise for an Animation. The getter returns that object. The important renewal rule is state-dependent, not method-name-dependent.

MDN summarizes the common case: each time an animation leaves the finished play state and begins playing again, a new finished Promise is created for the new sequence. The normative algorithm is more precise: when updating finished state, if the animation is not currently finished and its current finished Promise is already resolved, the current finished Promise is replaced by a new Promise.

For the replay defect, that gives this expected identity picture:

Moment

Animation identity

Raw finished handle

Expected settlement

Initial paused unfinished interval

A

p1

pending

First interval forced to finish

A

p1

fulfilled with A

Replay leaves finished state

A

p2

pending

Second interval forced to finish

A

p2

fulfilled with A

The animation remains A throughout. p1 !== p2.

That is the entire failure mechanism. The object is reused; the completion handle is not.

Keep the raw promise as the identity oracle

Identity evidence must preserve the getter result itself:

const p1 = animation.finished;
const again = animation.finished;

console.assert(p1 === again);

Do not substitute the Promise returned by .then(), .catch(), or an observation wrapper. MDN's Promise reference explains that chaining methods return new Promise objects and that attaching a handler to an already settled Promise still schedules the corresponding reaction asynchronously.

The fixture therefore uses an in-memory identity map:

const promiseIds = new WeakMap();
let nextPromiseId = 1;

function promiseLabel(promise) {
  if (!promiseIds.has(promise)) {
    promiseIds.set(promise, P${nextPromiseId++});
  }
  return promiseIds.get(promise);
}

The ledger serializes P1, P2, equality booleans, and settlement labels. It never tries to prove identity by stringifying a Promise.

A helper may observe both settlement branches, but its derived chain is bookkeeping only. The raw getter result remains the subject.

This is also why the shorthand “finished gives you the completion Promise” is inadequate for reusable animations. The precise question is: completion of which lifecycle interval?

3. Build an active-document laboratory with controlled time

The fixture uses an ordinary active document.timeline, one connected synthetic element, and one fresh native Animation per independent case. The effect is deliberately uninteresting:

new KeyframeEffect(
  node,
  [{ opacity: 0 }, { opacity: 1 }],
  {
    duration: 1000,
    iterations: 1,
    delay: 0,
    endDelay: 0,
    fill: "none"
  }
);

The animation uses playbackRate = 1. There is no zero duration, infinite iteration, rate zero, hidden-tab dependency, scroll timeline, framework scheduler, network request, or frame-cadence benchmark.

That matters because this is an explicit API-state experiment, not a timing benchmark. Refonte's separate requestAnimationFrame resume-delta validation asks how an animation loop treats elapsed time after document visibility changes. Here, time is controlled with pause(), currentTime, and finish().

Each case establishes the same baseline:

animation.pause();
await animation.ready;
animation.currentTime = 0;

Then it requires:

animation.playState === "paused";
animation.pending === false;
animation.currentTime === 0;

MDN describes pause() as suspending playback. The W3C ready-promise algorithm says the current ready Promise is replaced when a pending play or pause task is queued where there was no pending task; MDN likewise warns that one ready Promise can serve pending play and pause bookkeeping, so callers must inspect the resulting animation state.

ready therefore establishes a stable checkpoint. It is not treated as completion.

Before any real qualification run, freeze:

browserName       = <capture>
browserVersion    = <capture exact build/version>
engineVersion     = <capture if independently available>
operatingSystem   = <capture exact version/build>
fixtureRevision   = <git commit or immutable revision>
fixtureSha256     = <capture>
manifestSha256    = <capture>
runStartedAtUTC   = <capture>

Record these fields from the actual qualification environment.

Serve the fixture from localhost rather than opening it as an arbitrary file URL:

python3 -m http.server 8000

Then open the local test page.

The test establishes API state and Promise identity. It does not prove that a human saw every interpolated frame, that frame delivery was smooth, or that exactly 1000 milliseconds of wall-clock presentation occurred.

4. Author the case manifest before collecting browser evidence

The expected manifest is authored before runtime evidence so the test cannot quietly redefine success around whatever a particular run produces.

Case

Controlled action

Expected evidence

Publication state

A01

Read finished twice in stable paused unfinished baseline

Same raw object; pending observer; paused; currentTime=0

executed=false, observed=null, EXPECTED / NOT EXECUTED

A02

Capture p1, call finish(), await p1

Fulfills with same Animation; playState=finished; currentTime=1000

same

A03

Finish first interval; replay; capture p2; pause same turn; stabilize zero; attach cleanup to cached p1

p2 !== p1; old continuation runs before second finish; p2 still pending; early cleanup => REPAIR

same

A04

Same replay setup, but cleanup awaits p2 captured after replay

completion counter 0 before second finish, 1 after; p2 fulfills with Animation

same

A05

Finish; set currentTime=0; capture current finished; pause/stabilize

New raw handle differs from completed handle and remains pending

same

A06

Capture unfinished paused handle; play() then pause() same turn; stabilize below end

Raw finished identity unchanged and pending

same

A07

Observe pending unfinished handle; cancel

Captured handle rejects AbortError; idle/null times; getter returns different pending handle

same

A08

Finish and await historical handle; then cancel

Old handle remains fulfilled; getter changes; idle/null times

same

A09

Reproduce pending cancel; capture post-cancel handle; then play/pause/finish

New handle differs from canceled one; starting idle need not replace it again; current handle fulfills after finish

same

A10

Stable pause; play; capture pending ready and finished; install handlers; cancel before yielding

Both captured pending handles reject AbortError; new ready fulfilled for idle; new finished pending

same

Every case creates its own node and Animation. A03 does not hand state to A04. A07 does not prepare A08. Independence is itself a test property.

The ledger records at minimum:

caseId
animationId
executed
observed
expectationStatus
phase
operationOrder
cycleToken
promiseLabels
promiseEqualities
capturePhase
playState
pending
currentTime
startTime
settlementStatus
rejectionName
fulfilledWithExpectedAnimation
handlerPhase
completionCounter
permittedEffect
unexpectedErrors
cleanupStatus
runtimeTuple
fixtureRevision
fixtureSha256
manifestSha256

A sample empty case begins as:

{
  "caseId": "A03",
  "animationId": null,
  "executed": false,
  "observed": null,
  "expectationStatus": "EXPECTED / NOT EXECUTED",
  "phases": [],
  "unexpectedErrors": [],
  "cleanupStatus": null
}

The fixture's manifest inventory check must assert exactly ten distinct IDs, A01 through A10, with no duplicate.

Observe both settlement branches without changing the subject

Observation attaches handlers immediately after capture:

function observeRaw(label, raw, expectedAnimation, record) {
  const state = {
    rawLabel: promiseLabel(raw),
    status: "pending",
    rejectionName: null,
    fulfilledWithExpectedAnimation: null
  };

  const derived = raw.then(
    value => {
      state.status = "fulfilled";
      state.fulfilledWithExpectedAnimation = value === expectedAnimation;
    },
    error => {
      state.status = "rejected";
      state.rejectionName = error?.name ?? String(error);
    }
  );

  derived.catch(error => {
    record.unexpectedErrors.push({
      phase: "observer-derived-chain",
      name: error?.name ?? "Error",
      message: String(error?.message ?? error)
    });
  });

  return state;
}

The helper returns state, not a substitute Promise identity.

A microtask checkpoint is explicit:

async function microtaskCheckpoint() {
  await Promise.resolve();
}

That checkpoint has a bounded interpretation. If a handler was attached to an already fulfilled historical Promise, MDN's Promise semantics predict its reaction will be queued asynchronously. The test may establish that the historical callback ran while an independently verified second interval remained paused below its end. It may not infer that an arbitrary still-pending Promise “will never settle.”

A bounded watchdog similarly produces HOLD, not proof of impossibility.

5. Qualify one unfinished interval and its first completion

A01 establishes the boring control that makes later identity claims meaningful.

After creating a fresh connected node and Animation, pause it, await the current ready, and set currentTime=0. At that checkpoint the expected state is paused, not pending, and at zero. Capture:

const p1 = animation.finished;
const p1Again = animation.finished;

Expected A01 evidence is:

p1 === p1Again
observer(p1).status === "pending"
animation.playState === "paused"
animation.pending === false
animation.currentTime === 0

This prevents an overbroad rule such as “every getter read produces a new Promise.” It does not. Repeated reads within the same unfinished interval return the current object.

A02 uses a fresh fixture. Capture the unfinished p1, observe it, and call:

animation.finish();
await p1;

The specification's finish procedure seeks to the associated effect end in the current playback direction. For this finite forward effect, that limit is 1000. The normative algorithm uses the DOMException name InvalidStateError for invalid finish boundaries such as zero effective playback rate or positive playback toward an infinite end. MDN's displayed InvalidState wording is therefore not the terminology to use for that normative boundary.

For this controlled finite fixture, A02 expects:

p1 -> fulfilled
fulfillment value === animation
playState === "finished"
currentTime === 1000

Calling finish() is a control operation. It does not demonstrate natural elapsed playback. The Web Animations specification explicitly treats finish() as a special case where finish notification is performed synchronously as part of the procedure, although Promise handlers still execute through normal asynchronous job processing.

Most importantly, preserve p1.

Do not overwrite it with a later getter. Do not collapse its status into a single mutable animationFinished boolean. The test needs the first Promise object after the animation's current finished Promise eventually changes.

Historical settlement is evidence. It is not state pollution that must be erased.

6. Reproduce early cleanup from a cached fulfilled handle

A03 is the core negative control.

Start with a fresh fixture. Capture p1, attach its observer, call finish(), and await p1. At that point p1 is fulfilled and the first interval is complete.

Reset only the application's synthetic completion counter:

let completionCounter = 0;
let cycleToken = 2;

Now replay:

animation.play();
const p2 = animation.finished;
observeRaw("p2", p2, animation, record);

animation.pause(); // same synchronous turn as play()
await animation.ready;
animation.currentTime = 0;

MDN explicitly says that play() restarts an animation that is already finished. The expected consequence under the current-finished-promise algorithm is that the animation leaves its completed interval and has a new current finished Promise: p2 !== p1.

Verify the second interval independently:

playState === "paused"
pending === false
currentTime === 0
p2 !== p1
observer(p2).status === "pending"

Only now install the intentionally wrong cleanup:

const myToken = cycleToken;

p1.then(() => {
  if (myToken === cycleToken) {
    completionCounter++;
  }
});

Then cross the microtask checkpoint.

Expected evidence is:

completionCounter === 1
p1 observer === fulfilled
p2 observer === pending
animation paused at currentTime 0
second finish has not occurred

That is the bug in one controlled snapshot: the old fulfilled handle and the new pending handle coexist for the same Animation object.

The generation token deliberately matches. That proves an important limitation: a token cannot compensate for capturing the wrong lifecycle Promise when the stale callback is still associated with the current application operation.

Make the wrong-handle counterexample falsifiable

A useful negative control must show two independent facts.

First, the old callback actually executes. Second, the new playback interval is still unfinished when it executes.

Testing only the first fact is weak. An already fulfilled Promise is expected to run an attached continuation asynchronously. Testing only p1 therefore says nothing about replay ownership.

Testing only the second fact is also weak. A paused animation proves nothing about which Promise cleanup awaited.

A03 requires the cross-product:

old handle p1: fulfilled and its cleanup ran
new handle p2: distinct and still pending
animation: paused, pending=false, currentTime=0
completionCounter: 1
permittedEffect: false
decision: REPAIR

A negative control that reliably reproduces forbidden early cleanup is a successful diagnostic and a failed application behavior.

After this checkpoint, call finish() and await p2 so teardown does not confuse “test completed” with “animation lifecycle abandoned.” The early increment remains in the record.

No claim is made about visual presentation. This is lifecycle evidence only.

7. Capture the current handle after the replay transition

A04 repeats A03's application contract and changes one line of ownership.

Complete the first interval and preserve p1. Reset the synthetic counter. Start the intended replay, then capture the Promise that is current after that transition:

animation.play();
const p2 = animation.finished;

animation.pause();
await animation.ready;
animation.currentTime = 0;

Install cleanup on p2, not p1:

const myToken = cycleToken;

p2.then(() => {
  if (myToken === cycleToken) {
    completionCounter++;
  }
});

At the stable paused-zero checkpoint, after a microtask turn, expected evidence is:

p2 !== p1
p1 fulfilled
p2 pending
completionCounter === 0

Then:

animation.finish();
await p2;
await microtaskCheckpoint();

Expected evidence becomes:

p2 fulfilled with animation
completionCounter === 1

That is the repair: capture completion after the state-changing operation that begins the interval whose completion the application cares about.

Do not generalize it into “always read finished after play() regardless of state.” A06 will falsify that oversimplification. The rule is operation ownership, not method superstition.

Protect the operation token at the side-effect boundary

Promise ownership and application ownership solve different problems.

A correct current Promise tells you which animation lifecycle interval completed. A generation token tells you whether that completed interval is still permitted to mutate application state.

The minimal pattern is:

function authorizeReplayCompletion(animation, operation) {
  animation.play();

  const finishedForThisReplay = animation.finished;
  const token = operation.token;

  finishedForThisReplay.then(value => {
    if (value !== animation) return;
    if (operation.currentToken !== token) return;

    operation.completionCounter++;
  });
}

A current getter does not revoke a callback that was already queued from a historical fulfilled Promise. Promise reactions already scheduled remain jobs. The token is therefore checked at the side-effect boundary.

Refonte's latest-request UI ownership checks address the broader ownership idea in a different asynchronous domain. This article does not recreate that network-response fixture.

The narrow lesson here is:

correct Promise + wrong token => suppress stale application effect
wrong Promise + matching token => still wrong
correct Promise + matching token => eligible completion

Promise capture and generation ownership are complementary, not interchangeable.

8. Test seeking and unfinished pause-resume separately

A05 and A06 constrain the renewal rule so “new play call means new Promise” cannot survive the fixture.

A05 starts by completing an interval. Preserve:

const completed = animation.finished;
animation.finish();
await completed;

Then seek away from the finished endpoint:

animation.currentTime = 0;
const afterSeek = animation.finished;

The Web Animations update-finished-state algorithm says that if the animation is no longer in its current finished state while its current finished Promise is already resolved, that current Promise is replaced. Expected A05 evidence is therefore:

afterSeek !== completed
afterSeek pending
currentTime === 0

Pause and await current readiness if needed to establish the stable paused checkpoint, then verify the observer remains pending below the end.

This case matters because replay is not the only way to leave finished state. A seek can do it too.

A06 tests the opposite direction. Start from stable paused zero and capture:

const beforeResume = animation.finished;

Then, within the same synchronous turn:

animation.play();
animation.pause();
const afterCalls = animation.finished;

Await the current ready, stabilize below the endpoint, and compare identities.

The expected result is:

afterCalls === beforeResume
observer still pending

Why? The animation had not previously completed. Its current finished Promise was already the pending handle for this unfinished lifecycle. There is no fulfilled historical finished Promise that must be replaced merely because play() was invoked.

This is exactly where ready and finished must stay separate. The specification describes a single current ready Promise reused across certain pending play/pause interactions, and MDN's example warns authors to inspect final state after readiness because the pending operation can change before readiness resolves.

The fixture therefore performs same-turn control before yielding:

capture unfinished finished handle
play
pause
capture again
await current ready
verify paused/below-end
compare raw finished identities

A06's job is not to demonstrate replay. It is to prevent overfitting the replay result into a method-call heuristic.

9. Cancel a pending interval with explicit rejection evidence

A07 creates a fresh stable paused unfinished animation and captures its raw finished handle:

const pendingFinished = animation.finished;
const observation = observeRaw(
  "pending-before-cancel",
  pendingFinished,
  animation,
  record
);

Then cancel:

animation.cancel();

MDN's cancel() documentation says that canceling aborts playback, sets startTime and currentTime to null, and, when the animation was not already idle, rejects the current finished Promise with a DOMException named AbortError. The Web Animations specification likewise specifies synchronous cancel processing for current ready/finished Promise rejection and replacement.

Expected A07 evidence after microtask processing is:

pendingFinished -> rejected
rejectionName === "AbortError"
animation.playState === "idle"
animation.currentTime === null
animation.startTime === null
animation.finished !== pendingFinished
new animation.finished observer remains pending

The new idle-state finished Promise should not be awaited during teardown. It is intentionally pending until a later lifecycle operation gives it a completion path.

This is a Promise-lifecycle investigation, not an event-classification test. Refonte's CSS transition completion and cancellation article deals with transitionend and transitioncancel for CSS Transitions. Those events are not the acceptance predicate here.

A07 also proves why observing both fulfillment and rejection matters. A test that attaches only a fulfillment handler risks turning expected cancellation into an unhandled rejection or, worse, globally suppressing that error and losing the lifecycle evidence.

The fixture installs unhandledrejection capture before any case:

const unexpectedGlobal = [];

function onUnhandledRejection(event) {
  unexpectedGlobal.push({
    type: "unhandledrejection",
    reasonName: event.reason?.name ?? null,
    reasonMessage: String(event.reason?.message ?? event.reason)
  });
}

window.addEventListener("unhandledrejection", onUnhandledRejection);

It records the problem. It does not call preventDefault() merely to make the run look green.

10. Preserve fulfilled history across cancel and restart

A08 changes only the historical status before cancellation.

Create a fresh animation, capture historical, finish, and await it:

const historical = animation.finished;
animation.finish();
await historical;

The raw Promise is now fulfilled. Preserve its observation.

Then cancel:

animation.cancel();

Expected state:

historical remains fulfilled
animation.playState === "idle"
animation.currentTime === null
animation.startTime === null
animation.finished !== historical

The old Promise does not become rejected retroactively.

Never rewrite an old fulfilled result as a later rejection

This point reconciles the normative animation algorithm, MDN's convenient cancellation wording, and JavaScript Promise settlement.

MDN says the current finished Promise rejects with AbortError when a non-idle animation is canceled. That description concerns the Promise that is current for the cancel procedure's relevant lifecycle state. It does not mean every Promise object ever returned by animation.finished is mutable history.

JavaScript Promises settle once. An already fulfilled Promise remains fulfilled; attaching a handler later schedules the appropriate fulfillment reaction. The animation can replace which Promise its getter exposes without changing the settled state of an older object.

Therefore the ledger must say:

P1: historical handle, fulfilled
P2: current post-cancel handle, pending

not:

animation.finished: rejected

as though finished were one timeless Promise.

A09 tests the restart from cancellation independently. Begin with a pending handle, cancel it, observe AbortError, then capture the new post-cancel current finished handle:

const afterCancel = animation.finished;

Now:

animation.play();
const afterPlay = animation.finished;
animation.pause();
await animation.ready;
animation.currentTime = 0;

Expected identity is:

afterPlay === afterCancel

Starting from idle does not itself require another current-finished-Promise replacement because the post-cancel handle is already the pending Promise for the next unfinished interval. Finish the animation and expect that same handle to fulfill.

A08 and A09 together separate historical settlement, getter replacement, and subsequent reuse.

11. Use ready to synchronize bookkeeping, not completion

A10 makes ready and finished visible in the same cancel boundary.

Start from a stable unfinished pause. Then, without yielding:

animation.play();

const readyBeforeCancel = animation.ready;
const finishedBeforeCancel = animation.finished;

observePromise("ready", readyBeforeCancel, animation, record);
observeRaw("finished", finishedBeforeCancel, animation, record);

animation.cancel();

The order is deliberate. play() queues pending playback bookkeeping. The fixture captures both current handles while they are pending, installs both settlement branches, and cancels before the event loop gets a chance to satisfy the pending play request.

The Web Animations specification says cancellation rejects a pending current ready Promise with AbortError, replaces it with a new resolved ready Promise for the idle state, and rejects/replaces the relevant current finished Promise. MDN documents ready renewal both for entering pending operation state and for cancellation.

Expected A10 evidence is:

captured readyBeforeCancel -> rejected AbortError
captured finishedBeforeCancel -> rejected AbortError

animation.playState === "idle"
animation.pending === false
animation.currentTime === null
animation.startTime === null

animation.ready !== readyBeforeCancel
new current ready -> fulfilled with animation

animation.finished !== finishedBeforeCancel
new current finished -> pending

Do not call "pending" a playState. pending is its own boolean property. W3C exposes pending separately from playState, whose values describe idle/running/paused/finished state.

Also do not treat a fulfilled ready Promise as proof that the animation finished. Readiness belongs to pending playback bookkeeping. The MDN documentation specifically advises checking the animation's state when the ready Promise resolves because play and pause can share a current ready Promise across pending operations.

Nothing in A10 proves presentation to a user. It proves Promise and Animation state transitions at a controlled API boundary.

12. Clean up without concealing the first failing case

The teardown policy is ownership-preserving.

Every case owns exactly one synthetic element, one native Animation, its observers, and its ledger entry. The suite owns the global error listeners. Teardown may dispose of those resources; it may not delete evidence.

For an owned non-idle animation, relevant rejection handlers must already be attached before cancellation. Then:

if (animation.playState !== "idle") {
  animation.cancel();
}

node.remove();

Do not await animation.finished after teardown cancellation. The getter may now expose a new idle-state pending Promise, and awaiting it could stall forever without being evidence of a browser defect.

Remove only listeners installed by the fixture. Refonte's DOM listener identity and cleanup article covers the separate callback-identity problem in detail; this suite simply retains its listener references and removes those exact functions.

A bounded readiness watchdog looks like this:

async function withWatchdog(promise, ms, label) {
  let timer;
  try {
    return await Promise.race([
      promise,
      new Promise((_, reject) => {
        timer = setTimeout(() => {
          const error = new ErrorWatchdog: ${label});
          error.name = "WatchdogHold";
          reject(error);
        }, ms);
      })
    ]);
  } finally {
    clearTimeout(timer);
  }
}

A watchdog result means:

decision = HOLD
reason = readiness checkpoint did not complete within harness bound

It does not mean “the Promise can never settle.”

Recreate the case when lifecycle evidence is contaminated

A failed assertion, unexpected rejection, watchdog, or accidental lifecycle mutation does not justify repairing the object in place and continuing as though the case were clean.

Instead:

  1. retain the complete failed ledger;

  2. mark the case RERUN or HOLD;

  3. tear down only its owned resources;

  4. create a new node and new native Animation;

  5. rerun the case from phase zero under the same frozen runtime tuple.

Do not try to resurrect an old fulfilled Promise as though it were pending again. Do not suppress unhandledrejection globally. Do not mutate a ledger entry from failure to success and discard the first trace.

The fixture below implements these rules in one local page. Use the following HTML markup, and place the JavaScript shown after it in a script element at the end of the page's body.

HTML markup

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Animation.finished replay validation</title>
  <style>
    body { font-family: system-ui, sans-serif; }
    #fixture-root { position: fixed; left: -10000px; top: 0; }
    pre { white-space: pre-wrap; }
  </style>
</head>
<body>
  <button id="run">Run qualification fixture</button>
  <pre id="output"></pre>
  <div id="fixture-root"></div>

</body>
</html>

JavaScript

"use strict";

const EXPECTED_STATUS = "EXPECTED / NOT EXECUTED";
const CASE_IDS = [
  "A01","A02","A03","A04","A05",
  "A06","A07","A08","A09","A10"
];

const expectedManifest = Object.freeze({
  A01: {
    executed: false, observed: null, status: EXPECTED_STATUS,
    expected: "same raw finished object; pending; paused; currentTime=0"
  },
  A02: {
    executed: false, observed: null, status: EXPECTED_STATUS,
    expected: "captured finished fulfills with Animation; finished; currentTime=1000"
  },
  A03: {
    executed: false, observed: null, status: EXPECTED_STATUS,
    expected: "replay p2 differs from fulfilled p1; cached-p1 cleanup runs early; p2 pending"
  },
  A04: {
    executed: false, observed: null, status: EXPECTED_STATUS,
    expected: "p2 cleanup count 0 before second finish and 1 afterward"
  },
  A05: {
    executed: false, observed: null, status: EXPECTED_STATUS,
    expected: "seek away from finished replaces completed handle; replacement pending"
  },
  A06: {
    executed: false, observed: null, status: EXPECTED_STATUS,
    expected: "unfinished play/pause does not replace current finished handle"
  },
  A07: {
    executed: false, observed: null, status: EXPECTED_STATUS,
    expected: "pending finished rejects AbortError; idle/null times; getter replaced"
  },
  A08: {
    executed: false, observed: null, status: EXPECTED_STATUS,
    expected: "historical fulfilled handle remains fulfilled after cancel; getter changes"
  },
  A09: {
    executed: false, observed: null, status: EXPECTED_STATUS,
    expected: "post-cancel handle reused by idle restart and fulfills after finish"
  },
  A10: {
    executed: false, observed: null, status: EXPECTED_STATUS,
    expected: "captured pending ready/finished reject AbortError; new idle ready fulfilled; finished pending"
  }
});

const runtime = {
  browserName: "<capture>",
  browserVersion: "<capture exact build/version>",
  engineVersion: "<capture if independently available>",
  operatingSystem: "<capture exact version/build>",
  fixtureRevision: "<capture immutable revision>",
  fixtureSha256: "<capture>",
  manifestSha256: "<capture>",
  runStartedAtUTC: null
};

const promiseIds = new WeakMap();
let nextPromiseId = 1;
let nextAnimationId = 1;
const unexpectedGlobal = [];
const ledger = [];

function promiseLabel(p) {
  if (!promiseIds.has(p)) promiseIds.set(p, P${nextPromiseId++});
  return promiseIds.get(p);
}

function animationLabel(animation) {
  if (!animation.__fixtureId) {
    Object.defineProperty(animation, "__fixtureId", {
      value: AN${nextAnimationId++}
    });
  }
  return animation.__fixtureId;
}

function snapshot(animation) {
  return {
    playState: animation.playState,
    pending: animation.pending,
    currentTime: animation.currentTime,
    startTime: animation.startTime
  };
}

function phase(record, name, animation, extra = {}) {
  record.phases.push({
    name,
    state: animation ? snapshot(animation) : null,
    ...extra
  });
}

function assert(record, condition, message) {
  if (!condition) {
    const error = new Error(message);
    record.unexpectedErrors.push({
      phase: record.phases.at(-1)?.name ?? null,
      name: error.name,
      message
    });
    throw error;
  }
}

function observeRaw(label, raw, expectedAnimation, record) {
  const observation = {
    subject: label,
    rawLabel: promiseLabel(raw),
    status: "pending",
    rejectionName: null,
    fulfilledWithExpectedAnimation: null,
    handlerPhase: null
  };

  record.promiseObservations.push(observation);

  const derived = raw.then(
    value => {
      observation.status = "fulfilled";
      observation.fulfilledWithExpectedAnimation =
        value === expectedAnimation;
      observation.handlerPhase =
        record.phases.at(-1)?.name ?? "between-phases";
    },
    error => {
      observation.status = "rejected";
      observation.rejectionName =
        error?.name ?? String(error);
      observation.handlerPhase =
        record.phases.at(-1)?.name ?? "between-phases";
    }
  );

  derived.catch(error => {
    record.unexpectedErrors.push({
      phase: "observer-derived-chain",
      name: error?.name ?? "Error",
      message: String(error?.message ?? error)
    });
  });

  return observation;
}

function observePromise(label, promise, expectedAnimation, record) {
  return observeRaw(label, promise, expectedAnimation, record);
}

async function microtaskCheckpoint() {
  await Promise.resolve();
}

async function withWatchdog(promise, ms, label) {
  let timer;
  try {
    return await Promise.race([
      promise,
      new Promise((_, reject) => {
        timer = setTimeout(() => {
          const e = new ErrorWatchdog expired: ${label});
          e.name = "WatchdogHold";
          reject(e);
        }, ms);
      })
    ]);
  } finally {
    clearTimeout(timer);
  }
}

function makeRecord(caseId) {
  return {
    caseId,
    animationId: null,
    executed: true,
    observed: {},
    expectationStatus: EXPECTED_STATUS,
    decision: null,
    operationOrder: [],
    cycleToken: null,
    promiseObservations: [],
    promiseEqualities: [],
    phases: [],
    unexpectedErrors: [],
    cleanupStatus: null,
    runtime: { ...runtime }
  };
}

function makeFixture(record) {
  const root = document.querySelector("#fixture-root");
  const node = document.createElement("div");
  node.textContent = record.caseId;
  root.append(node);

  const effect = new KeyframeEffect(
    node,
    [{ opacity: 0 }, { opacity: 1 }],
    {
      duration: 1000,
      iterations: 1,
      delay: 0,
      endDelay: 0,
      fill: "none"
    }
  );

  const animation = new Animation(effect, document.timeline);
  animation.playbackRate = 1;
  record.animationId = animationLabel(animation);

  return { node, animation };
}

async function stablePausedZero(record, animation) {
  phase(record, "baseline-before-pause", animation);
  animation.pause();
  record.operationOrder.push("pause");

  await withWatchdog(animation.ready, 2000, ${record.caseId}:ready);
  record.operationOrder.push("await-ready");

  animation.currentTime = 0;
  record.operationOrder.push("currentTime=0");
  phase(record, "stable-paused-zero", animation);

  assert(record, animation.playState === "paused", "expected paused");
  assert(record, animation.pending === false, "expected pending=false");
  assert(record, animation.currentTime === 0, "expected currentTime=0");
}

async function teardown(record, fixture) {
  try {
    if (fixture.animation.playState !== "idle") {
      const current = fixture.animation.finished;
      observeRaw(
        "teardown-current-finished",
        current,
        fixture.animation,
        record
      );
      fixture.animation.cancel();
    }
  } catch (error) {
    record.unexpectedErrors.push({
      phase: "teardown",
      name: error?.name ?? "Error",
      message: String(error?.message ?? error)
    });
  } finally {
    fixture.node.remove();
    record.cleanupStatus = "fixture-owned node removed";
  }
}

async function A01(record, animation) {
  await stablePausedZero(record, animation);
  const p1 = animation.finished;
  const p1Again = animation.finished;
  const o1 = observeRaw("p1", p1, animation, record);

  record.promiseEqualities.push({
    left: promiseLabel(p1),
    right: promiseLabel(p1Again),
    equal: p1 === p1Again
  });

  await microtaskCheckpoint();
  phase(record, "observe", animation);

  assert(record, p1 === p1Again, "A01 raw promises differ");
  assert(record, o1.status === "pending", "A01 p1 not pending");
}

async function A02(record, animation) {
  await stablePausedZero(record, animation);
  const p1 = animation.finished;
  const o1 = observeRaw("p1", p1, animation, record);
  phase(record, "pre-finish-capture", animation);

  animation.finish();
  record.operationOrder.push("finish");
  await p1;
  await microtaskCheckpoint();
  phase(record, "after-finish", animation);

  assert(record, o1.status === "fulfilled", "A02 not fulfilled");
  assert(record, o1.fulfilledWithExpectedAnimation === true,
    "A02 wrong fulfillment value");
  assert(record, animation.playState === "finished",
    "A02 expected finished");
  assert(record, animation.currentTime === 1000,
    "A02 expected currentTime=1000");
}

async function setupCompletedInterval(record, animation) {
  await stablePausedZero(record, animation);
  const p1 = animation.finished;
  const o1 = observeRaw("historical-p1", p1, animation, record);
  animation.finish();
  await p1;
  await microtaskCheckpoint();
  assert(record, o1.status === "fulfilled",
    "historical promise did not fulfill");
  return { p1, o1 };
}

async function replayPausedZero(record, animation) {
  animation.play();
  record.operationOrder.push("play");
  const p2 = animation.finished;
  const o2 = observeRaw("replay-p2", p2, animation, record);

  animation.pause();
  record.operationOrder.push("pause-same-turn");
  await withWatchdog(animation.ready, 2000, ${record.caseId}:replay-ready);
  animation.currentTime = 0;
  phase(record, "replay-paused-zero", animation);

  assert(record, animation.playState === "paused", "expected replay paused");
  assert(record, animation.pending === false, "expected replay pending=false");
  assert(record, animation.currentTime === 0, "expected replay at zero");

  return { p2, o2 };
}

async function A03(record, animation) {
  const { p1 } = await setupCompletedInterval(record, animation);
  let completionCounter = 0;
  let currentToken = 2;
  const capturedToken = currentToken;
  record.cycleToken = capturedToken;

  const { p2, o2 } = await replayPausedZero(record, animation);

  record.promiseEqualities.push({
    left: promiseLabel(p1),
    right: promiseLabel(p2),
    equal: p1 === p2
  });

  p1.then(() => {
    if (capturedToken === currentToken) completionCounter++;
  }).catch(error => {
    record.unexpectedErrors.push({
      phase: "A03-cleanup-chain",
      name: error?.name ?? "Error",
      message: String(error?.message ?? error)
    });
  });

  await microtaskCheckpoint();
  phase(record, "wrong-handle-microtask-checkpoint", animation, {
    completionCounter,
    p2Status: o2.status
  });

  assert(record, p1 !== p2, "A03 p2 must differ from p1");
  assert(record, completionCounter === 1,
    "A03 stale cleanup did not reproduce");
  assert(record, o2.status === "pending",
    "A03 replay promise should still be pending");

  record.observed.permittedEffect = false;
  record.decision = "REPAIR";

  animation.finish();
  await p2;
}

async function A04(record, animation) {
  const { p1 } = await setupCompletedInterval(record, animation);
  let completionCounter = 0;
  let currentToken = 2;
  const capturedToken = currentToken;
  record.cycleToken = capturedToken;

  const { p2 } = await replayPausedZero(record, animation);

  p2.then(() => {
    if (capturedToken === currentToken) completionCounter++;
  }).catch(error => {
    record.unexpectedErrors.push({
      phase: "A04-cleanup-chain",
      name: error?.name ?? "Error",
      message: String(error?.message ?? error)
    });
  });

  await microtaskCheckpoint();
  phase(record, "before-second-finish", animation, {
    completionCounter
  });

  assert(record, p1 !== p2, "A04 expected distinct replay promise");
  assert(record, completionCounter === 0,
    "A04 cleanup ran before completion");

  animation.finish();
  await p2;
  await microtaskCheckpoint();

  phase(record, "after-second-finish", animation, {
    completionCounter
  });

  assert(record, completionCounter === 1,
    "A04 cleanup count should be one");
}

async function A05(record, animation) {
  const { p1 } = await setupCompletedInterval(record, animation);

  animation.currentTime = 0;
  record.operationOrder.push("seek-currentTime=0");

  const p2 = animation.finished;
  const o2 = observeRaw("post-seek-p2", p2, animation, record);

  animation.pause();
  await withWatchdog(animation.ready, 2000, "A05-ready");
  animation.currentTime = 0;
  await microtaskCheckpoint();

  record.promiseEqualities.push({
    left: promiseLabel(p1),
    right: promiseLabel(p2),
    equal: p1 === p2
  });

  assert(record, p1 !== p2, "A05 expected renewed promise");
  assert(record, o2.status === "pending", "A05 p2 expected pending");
}

async function A06(record, animation) {
  await stablePausedZero(record, animation);

  const p1 = animation.finished;
  const o1 = observeRaw("unfinished-p1", p1, animation, record);

  animation.play();
  animation.pause();
  const p2 = animation.finished;

  await withWatchdog(animation.ready, 2000, "A06-ready");
  animation.currentTime = 0;
  await microtaskCheckpoint();

  record.promiseEqualities.push({
    left: promiseLabel(p1),
    right: promiseLabel(p2),
    equal: p1 === p2
  });

  assert(record, p1 === p2, "A06 unexpectedly renewed finished");
  assert(record, o1.status === "pending", "A06 handle should remain pending");
}

async function A07(record, animation) {
  await stablePausedZero(record, animation);

  const p1 = animation.finished;
  const o1 = observeRaw("pending-before-cancel", p1, animation, record);

  animation.cancel();
  await microtaskCheckpoint();

  const p2 = animation.finished;
  const o2 = observeRaw("post-cancel-current", p2, animation, record);

  phase(record, "after-cancel", animation);

  assert(record, o1.status === "rejected", "A07 p1 not rejected");
  assert(record, o1.rejectionName === "AbortError",
    "A07 expected AbortError");
  assert(record, animation.playState === "idle", "A07 expected idle");
  assert(record, animation.currentTime === null, "A07 currentTime not null");
  assert(record, animation.startTime === null, "A07 startTime not null");
  assert(record, p2 !== p1, "A07 getter did not change");
  assert(record, o2.status === "pending", "A07 new finished not pending");
}

async function A08(record, animation) {
  const { p1, o1 } = await setupCompletedInterval(record, animation);

  animation.cancel();
  await microtaskCheckpoint();

  const p2 = animation.finished;
  observeRaw("post-cancel-p2", p2, animation, record);

  assert(record, o1.status === "fulfilled",
    "A08 historical fulfillment changed");
  assert(record, p2 !== p1, "A08 getter should change");
  assert(record, animation.playState === "idle", "A08 expected idle");
  assert(record, animation.currentTime === null, "A08 currentTime not null");
  assert(record, animation.startTime === null, "A08 startTime not null");
}

async function A09(record, animation) {
  await stablePausedZero(record, animation);

  const canceled = animation.finished;
  const canceledObs = observeRaw("canceled-handle", canceled, animation, record);
  animation.cancel();
  await microtaskCheckpoint();

  assert(record, canceledObs.rejectionName === "AbortError",
    "A09 cancellation did not reject AbortError");

  const postCancel = animation.finished;
  const postCancelObs =
    observeRaw("post-cancel-current", postCancel, animation, record);

  animation.play();
  const afterPlay = animation.finished;

  animation.pause();
  await withWatchdog(animation.ready, 2000, "A09-ready");
  animation.currentTime = 0;

  assert(record, postCancel !== canceled,
    "A09 post-cancel handle should differ");
  assert(record, afterPlay === postCancel,
    "A09 idle play unexpectedly replaced current finished");

  animation.finish();
  await postCancel;
  await microtaskCheckpoint();

  assert(record, postCancelObs.status === "fulfilled",
    "A09 post-cancel handle did not fulfill");
}

async function A10(record, animation) {
  await stablePausedZero(record, animation);

  animation.play();

  const ready1 = animation.ready;
  const finished1 = animation.finished;

  const r1 = observePromise("captured-ready", ready1, animation, record);
  const f1 = observeRaw("captured-finished", finished1, animation, record);

  assert(record, animation.pending === true,
    "A10 expected pending before cancel");

  animation.cancel();
  await microtaskCheckpoint();

  const ready2 = animation.ready;
  const finished2 = animation.finished;

  const r2 = observePromise("idle-ready", ready2, animation, record);
  const f2 = observeRaw("idle-finished", finished2, animation, record);

  await microtaskCheckpoint();

  assert(record, r1.status === "rejected", "A10 ready1 not rejected");
  assert(record, r1.rejectionName === "AbortError",
    "A10 ready1 expected AbortError");
  assert(record, f1.status === "rejected", "A10 finished1 not rejected");
  assert(record, f1.rejectionName === "AbortError",
    "A10 finished1 expected AbortError");

  assert(record, ready2 !== ready1, "A10 ready getter not replaced");
  assert(record, finished2 !== finished1,
    "A10 finished getter not replaced");
  assert(record, r2.status === "fulfilled",
    "A10 idle ready expected fulfilled");
  assert(record, f2.status === "pending",
    "A10 idle finished expected pending");
}

const caseFns = { A01,A02,A03,A04,A05,A06,A07,A08,A09,A10 };

function onError(event) {
  unexpectedGlobal.push({
    type: "error",
    message: event.message,
    filename: event.filename,
    lineno: event.lineno,
    colno: event.colno
  });
}

function onUnhandledRejection(event) {
  unexpectedGlobal.push({
    type: "unhandledrejection",
    reasonName: event.reason?.name ?? null,
    reasonMessage: String(event.reason?.message ?? event.reason)
  });
}

window.addEventListener("error", onError);
window.addEventListener("unhandledrejection", onUnhandledRejection);

function validateManifest() {
  const ids = Object.keys(expectedManifest);
  if (ids.length !== 10) throw new Error("Manifest must contain 10 cases");
  if (new Set(ids).size !== 10) throw new Error("Duplicate manifest case ID");

  for (const expected of CASE_IDS) {
    if (!ids.includes(expected)) {
      throw new ErrorMissing manifest case ${expected});
    }
  }
}

async function runAll() {
  validateManifest();
  runtime.runStartedAtUTC = new Date().toISOString();
  ledger.length = 0;

  for (const caseId of CASE_IDS) {
    const record = makeRecord(caseId);
    ledger.push(record);
    const fixture = makeFixture(record);

    try {
      phase(record, "setup", fixture.animation);
      await caseFns[caseId](record, fixture.animation);

      if (!record.decision) {
        record.decision =
          record.unexpectedErrors.length === 0 ? "EXPECTED-MATCH" : "HOLD";
      }
    } catch (error) {
      record.decision =
        error?.name === "WatchdogHold" ? "HOLD" : "RERUN";
      record.unexpectedErrors.push({
        phase: "case-runner",
        name: error?.name ?? "Error",
        message: String(error?.message ?? error)
      });
    } finally {
      await teardown(record, fixture);
    }
  }

  return {
    runtime,
    expectedManifest,
    ledger,
    unexpectedGlobal
  };
}

document.querySelector("#run").addEventListener("click", async () => {
  const output = document.querySelector("#output");
  output.textContent = "Running…";

  const result = await runAll();
  output.textContent = JSON.stringify(result, null, 2);

  console.log("ANIMATION_FINISHED_REPLAY_EVIDENCE", result);
});

The source code above is a proposed runnable fixture, not an executed result. A qualification run should save both the source and emitted JSON, hash the source and manifest, and preserve console/runtime evidence.

13. Choose a release decision from the complete ownership record

The decision must reconcile API contract, raw object identity, application side effects, and run provenance.

Decision

Required evidence

Meaning

ACCEPT

Frozen runtime tuple; all required cases executed independently; raw identities and settlements match the reviewed contract; A03 reproduces forbidden early cleanup; A04 permits cleanup only after replay completion; no unexplained global errors

Implementation and qualification evidence agree

REPAIR

Fixture proves application code binds completion to a historical handle, permits A03-style early effect, omits current-handle capture, or performs a side effect with stale ownership

Change code and associated regression tests before release

RERUN

Case setup contaminated, assertion infrastructure failed, resource ownership leaked, manual interference occurred, or evidence is incomplete but the contract itself is not disputed

Preserve the failed ledger, create fresh node/Animation, rerun

RECONCILE

Browser evidence is internally coherent but differs from the independently authored expectation and current normative/reference interpretation

Compare specification algorithms, browser implementation, and possibly implementation bugs before changing expected results

HOLD

Runtime tuple missing; fixture not executed; watchdog fired; Promise identity not retained; unexpected failures remain unresolved; or browser behavior cannot yet be reconciled

Do not publish a conformance or acceptance claim

Until the fixture has been executed and its runtime evidence retained, the qualification decision remains:

HOLD
reason:
  No browser laboratory executed.
  All A01–A10 outcomes remain EXPECTED / NOT EXECUTED.
  executed=false
  observed=null
  runtime tuple=<uncaptured>

Responsibility should also be explicit. Code ownership belongs to the frontend code that chooses which Promise authorizes the side effect. Test ownership belongs to the harness that records raw identities, settlements, state checkpoints, and negative controls. Release ownership belongs to the process that refuses to turn authored expectations into “PASS” without a complete runtime record.

The acceptance record should include all ten case entries even when one fails. A failure in A03 is special: the expected negative-control behavior is that the buggy application pattern increments the counter too early. If that reproduction occurs exactly as expected, the diagnostic case itself matches its manifest while the demonstrated application pattern remains REPAIR.

Likewise, a browser deviation must not be normalized away. Suppose a future engine returns the same raw finished Promise after a completed animation is replayed, contrary to the reviewed current-promise renewal contract. The correct publication action is not to modify the expectation until the test passes. Preserve the evidence, mark RECONCILE or HOLD, and review the normative algorithm and implementation.

The fixture also has strict material limits. It does not measure natural animation duration, rendered-frame cadence, display presentation, accessibility outcomes, durable storage effects, or user-visible completion. finish() changes API state deliberately. A paused-zero checkpoint proves an unfinished API interval, not what pixels a particular compositor displayed.

The decisive invariant is compact enough to put in the test review checklist:

Animation identity != playback-cycle identity

historical finished Promise:
  valid evidence of the interval it settled for

current finished Promise:
  completion handle for the current unfinished interval

application completion:
  permitted only when the current interval's handle settles
  AND the application-owned operation token is still current

That is the release rule the ten cases are designed to defend.

14. Develop browser-lifecycle skills with Refonte Learning

This investigation is a JavaScript lifecycle exercise more than an animation-design exercise. It requires reading a normative state machine, distinguishing object identity from operation identity, preserving raw asynchronous evidence, designing negative controls, and testing cleanup ownership instead of merely checking a final DOM value.

Refonte Learning's Frontend Development Program describes curriculum covering HTML5/CSS3, JavaScript ES6+, responsive design, React components, Redux, APIs/AJAX, Git, accessibility, performance optimization, and a capstone project. Its page also lists Git, npm, React, and Visual Studio Code in its FAQ and describes potential internship participation and certificates on successful completion. These program details do not constitute job-placement guarantees.

Engineers who want broader practice with the JavaScript, CSS, tooling, accessibility, and frontend-development foundations behind this kind of lifecycle reasoning can review the Frontend Development Program.

The narrower engineering conclusion remains independent of any training program: capture the completion handle owned by the playback interval you actually started. A fulfilled historical Animation.finished Promise is legitimate history, but it is not authorization for the next replay.