namdmyr
namdmyr

Reputation: 21

Reset setInterval within setTimeout at click of button

I'm currently noodling around with an animation project using transitions but I've run in to a problem that seem so simple, yet I'm completely lost.

I have two buttons to cycle between characters, who in turn have different animations based on the current state. So when I click the button I want to:

My problem is I can't make it run from the start every time. For example, the very first time an animation runs it goes from top to bottom. But if I click the button to switch character it might, after the "run-animation" is added, jump straight to for example "state-three". I need a way to "reset" "state" everytime I click the button to switch character. Also, the state-classes sometimes overlap, as in adding for example both "state-two" and "state-three".

I've tried different ways of clearInterval(), clearTimeout() etc but without any success.

Below is the code I'm currently running for the button and the function.

 $("#button").click(function () {
    $("#character").removeClass();
    $("#character").addClass("exampleCharacter");
    setTimeout(function () {
      $("#character").addClass("run-animation");
      state(".run-animation");
    }, 2000);
  });

 function state(e) {
   setInterval(function() {
     $(e).removeClass("state-four");
     setTimeout(function () {
       $(e).addClass("state-two");
     }, 1000);
     setTimeout(function () {
       $(e).removeClass("state-two");
       $(e).addClass("state-three");
     }, 2000);
     setTimeout(function () {
       $(e).removeClass("state-three");
       $(e).addClass("state-four");
     }, 3000);
   }, 4000)
 }

Upvotes: 2

Views: 74

Answers (1)

namdmyr
namdmyr

Reputation: 21

"Solved" the problem by adding reference to all Intervals and Timeouts (including those in state-function) in global variables which are cleared at the button click. Messy code and probably not the optimal solution but at least it works for now.

Upvotes: 0

Related Questions