How to reset an animation with step?

Viewed 28

myFun = () => {
    $('.test').animate({ now: 100}, {
        duration: 1000,
        complete: function() {
            now = 0;
        },
        step: function(now) {
            console.log(now);
        }
    });
}

myFun();
myFun();
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="test"></div>    

I've this function:

myFun = () => {
    $('.test').animate({ now: 100}, {
        duration: 1000,
        step: function(now) {
            console.log(now);
        }
    });
}


myFun();
myFun();

If I call it twice, the second time now remains fixed at 100. I tried to solve like this:

myFun = () => {
    $('.test').animate({ now: 100}, {
        duration: 1000,
        complete: function() {
            now = 0;
        },
        step: function(now) {
            console.log(now);
        }
    });
}

but it doesn't work. How do I reset now?

(In general I need to repeat an animation with the step function)

1 Answers

There is tow things you will have to look at. First, you cant trigger a myFun without waiting for the animation to complete for the first run.

And that is why I made myFun return a Promise and resolve it in complete function.

The second issue, I do not think that there is any way to reset the step without running animate again and reset it to 0 again.

And that is why I added another animate that will reset the step to 0.

Have a look below and let me know if you do not understand.

myFun = (t) => {
   return new Promise((r)=> {
    $('.test').animate({ now: 0},{
    complete:()=> {
    $('.test').animate({ now: 100}, {
        duration: 1000,
        complete: function() {
            now = 0;
            r();
        },
        step: function(now) {
            console.log(t, ":", now);
        }
    });
   }})
   })
}

myFun(1).then(x=>myFun(2) );

 
.test {
  background: red;
  width: 100%;
  min-height: 3px;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="test"></div>

Related