qwerty
qwerty

Reputation: 49

Why does calling an animation function multiple times cause it to skip animations in three js?

I want to repeat an animation group (the sphere moving then the rectangle) then write the number of times it has been repeated in the div named expected_output. But for some reason it skips the animation, i.e. the animation doesnt start.

Here is the function code:

  var j = 1
  var fieldNameElement = document.getElementById("expected_output");
  function animator_repeat(){ 
    const animationClip = new THREE.AnimationClip(null,3, [track1]);
    const animationClip1 = new THREE.AnimationClip(null,3, [track]);
    const animationAction = mesh.userData.mixer.clipAction(animationClip);
    const animationAction1 = cube.userData.mixer.clipAction(animationClip1);

    animationAction.setLoop(THREE.LoopRepeat ,1);
    animationAction.play();
    mesh.userData.mixer.addEventListener( 'finished', () => {

      animationAction1.setLoop(THREE.LoopRepeat ,1);
          animationAction1.play(); 
          cube.userData.mixer.addEventListener( 'finished', () => {
          if(j<6){
             fieldNameElement.textContent = "Number: "+(j+1).toString();
             animator_repeat() 
             j = j+1 
            }
          });
     } )
  }

Here is the jsfiddle: https://jsfiddle.net/xgnj4fbh/6/

As you can see it skips, 3,4

Could someone explain whats going wrong?

Thanks

Upvotes: 0

Views: 333

Answers (1)

Jay Li
Jay Li

Reputation: 747

This is because you are adding new event every time the animation is finished. Every time animator_repeat() is called, mesh gets a new finish event, and every time mesh finishes, cube gets a new finish event, and when cube finishes it calls animator_repeat().

So the 2nd time cube finishes, it runs finish event 3 times which added j from 2 straight to 5.

Solutions would be to remove old events before adding new one, or add named function instead of an anonymous one.

Upvotes: 1

Related Questions