Loop Three.js Animation a Specific Number of Times

Controlling the repetition of animations in Three.js is crucial for creating precise interactive 3D experiences. This guide explains how to configure the AnimationMixer and AnimationAction to loop a specific animation a set number of times rather than playing it infinitely, complete with practical code examples.

To limit the number of times an animation plays in Three.js, you must configure the AnimationAction object returned by your AnimationMixer. This is achieved using the setLoop method.

Step-by-Step Implementation

  1. Get the AnimationAction: Create an action from your mixer using your animation clip.
  2. Configure the Loop Mode: Call setLoop on the action, passing THREE.LoopRepeat (or THREE.LoopPingPong) as the first argument, and your desired repetition count as the second argument.
  3. Play the Animation: Call the play() method.

Here is the essential code to loop an animation exactly 3 times:

import * as THREE from 'three';

// 1. Initialize the mixer and get the action
const mixer = new THREE.AnimationMixer(myMesh);
const action = mixer.clipAction(myAnimationClip);

// 2. Set the loop mode and the number of repetitions (e.g., 3 times)
action.setLoop(THREE.LoopRepeat, 3);

// Optional: Keep the mesh at the last frame when finished
action.clampWhenFinished = true;

// 3. Play the animation
action.play();

Understanding the Parameters

The setLoop method accepts two parameters:

Handling the Finished Event

If you want to trigger an action (such as loading a new animation or UI change) after the loop finishes, you can listen to the mixer’s finished event:

mixer.addEventListener('finished', (event) => {
    if (event.action === action) {
        console.log("Animation completed its specified loops.");
        // Add your custom logic here
    }
});