Skip to content

fix: emit finished event for one time animation#5179

Merged
diegoteran merged 2 commits into
google:masterfrom
vincentfretin:fix-emit-finished-event
Jun 16, 2026
Merged

fix: emit finished event for one time animation#5179
diegoteran merged 2 commits into
google:masterfrom
vincentfretin:fix-emit-finished-event

Conversation

@vincentfretin

Copy link
Copy Markdown
Contributor

That's a regression from 4.3.0 with the multi-model refactor.
You can see the "Change animation speed" example at https://modelviewer.dev/examples/animation/ is currently broken, it doesn't emit finished event to play again the animation at different speed.

Claude Opus 4.8 did the fix. I confirm the robot example is working with those changes.
The multi-model refactor recreates the animation mixers on every setSource(), but the mixer event subscriptions (registered once when the animation feature is constructed, before any model is loaded) were not re-applied to the new mixers, so the 'finished' event was never dispatched.

@vincentfretin vincentfretin force-pushed the fix-emit-finished-event branch from 12a321a to 6bc23ee Compare June 15, 2026 08:58
Two separate bugs prevented the 'finished' event from being dispatched
when an animation was played a single time (repetitions: 1):

1. Mixer event subscriptions were lost on model load (regression from
   4.3.0). The multi-model refactor recreates the animation mixers on
   every setSource(), but the mixer event subscriptions are registered
   only once, when the animation feature is constructed — before any
   model is loaded, while there are no mixers yet. They were never
   re-applied to the mixers created later, so 'finished' (and 'loop')
   were never dispatched. ModelScene now remembers its subscriptions and
   attaches them to every mixer it creates.

2. Setting the animationName property and then calling play() looped
   forever (present in all versions). Assigning animationName schedules
   an asynchronous reactive update whose updated() re-triggers playback;
   it did so with the default options (repetitions: Infinity /
   LoopRepeat), overwriting a play({repetitions: 1}) issued in the same
   tick, so the clip looped and never finished. Using the declarative
   animation-name attribute avoided this only because the property never
   changed. play() now records its options and the re-trigger reuses them
   instead of resetting to an infinite loop.

Both paths are covered by regression tests in animation-spec.ts.
@vincentfretin vincentfretin force-pushed the fix-emit-finished-event branch from 6bc23ee to 933efc8 Compare June 15, 2026 09:20
@vincentfretin

vincentfretin commented Jun 15, 2026

Copy link
Copy Markdown
Contributor Author

I also fixed another issue, this code never worked in any versions (at least on 4.1.0 when I first tried it)

modelViewer.animationName = "open";
modelViewer.currentTime = 0;
modelViewer.play({ repetitions: 1 });

it looped the animation instead of running it only once and emitting finished event.

With the change of this PR I can finally do this for a door model with an open and close animations, animation-crossfade-duration="0" and no autoplay on model-viewer tag, and a button to switch the animation:

    <script type="module">
      // Toggle button to play the "open" / "close" animations. Closed is the default.
      const modelViewer = document.querySelector("model-viewer");

      const button = document.createElement("button");
      button.type = "button";
      button.className = "animation-toggle";

      let isOpen = false; // closed by default
      let isPlaying = false;

      function render() {
        // label shows the action the button performs
        button.textContent = isOpen ? "Close" : "Open";
        button.disabled = isPlaying;
      }

      button.addEventListener("click", () => {
        if (isPlaying) return;
        const currentAnim = isOpen ? "close" : "open";
        modelViewer.animationName = currentAnim;
        // Restart from the first frame. A finished animation is left clamped on
        // its last frame, so replaying it would otherwise show the end pose
        // (e.g. the door already open) right away instead of animating.
        modelViewer.currentTime = 0;
        modelViewer.play({ repetitions: 1 });
        isPlaying = true;
        render();
      });
      const listener = () => {
        isPlaying = false;
        isOpen = !isOpen;
        render();
      };
      modelViewer.addEventListener("finished", listener);

      render();
      modelViewer.insertAdjacentElement("afterend", button);
    </script>

instead of the crazy workaround I had to do in 4.1.0 with the appendAnimation api:

    <script type="module">
      // Toggle button to play the "open" / "close" animations. Closed is the default.
      const modelViewer = document.querySelector("model-viewer");

      const button = document.createElement("button");
      button.type = "button";
      button.className = "animation-toggle";

      let isOpen = false; // closed by default
      let isPlaying = false;

      function render() {
        // label shows the action the button performs
        button.textContent = isOpen ? "Close" : "Open";
        button.disabled = isPlaying;
      }

      button.addEventListener("click", () => {
        if (isPlaying) return;
        const currentAnim = isOpen ? "close" : "open";
        // Setting modelViewer.animationName + play({ repetitions: 1 }) doesn't emit "finished",
        // so append every animation once (weight 0 for the others) and wait for them all to finish.
        modelViewer.availableAnimations.forEach((animationName) => {
          if (animationName !== currentAnim) {
            modelViewer.appendAnimation(animationName, { weight: 0, repetitions: 1 });
          }
        });
        modelViewer.appendAnimation(currentAnim, { weight: 1, repetitions: 1 });
        isPlaying = true;
        render();
        let countFinished = 0;
        const listener = () => {
          countFinished++;
          if (countFinished === modelViewer.availableAnimations.length) {
            isPlaying = false;
            isOpen = !isOpen;
            render();
            modelViewer.removeEventListener("finished", listener);
          }
        };
        modelViewer.addEventListener("finished", listener);
      });

      render();
      modelViewer.insertAdjacentElement("afterend", button);
    </script>

Demonstrate playing an animation a single time on demand: set animationName, reset currentTime to 0, call play({repetitions: 1}), and re-enable the control on the 'finished' event. Doubles as a live test of the one-time-animation finished fix.
@vincentfretin

Copy link
Copy Markdown
Contributor Author

I added an example in animation doc page with that exact use case.

@diegoteran diegoteran left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thank you for the documentation too

@diegoteran diegoteran merged commit 111348d into google:master Jun 16, 2026
7 checks passed
@vincentfretin vincentfretin deleted the fix-emit-finished-event branch June 17, 2026 06:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants