Bridgbro
Bridgbro

Reputation: 269

How to Stop a Recursive Function in JavaScript?

I'm stuck looking for the right way to stop a setTimeout call recursive function. I want to be able to restart an animation without having to wait for the animation to finish.

Any help would be awesome!!

var viewArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var started = 0;

function animator() {
  if (!started) {
    console.log("Start... ");
    started = 1;
    var i = 0;
    count = 1;

    (function iterator() { // <-- how can I kill this iterator function when the user clicks stop
      document.getElementById("output").innerHTML = viewArray[i];
      if (++i < viewArray.length) {
        setTimeout(iterator, 1000);
        count++
        if (count >= viewArray.length) {
          started = 0;
        } //when animation complete (number reaches 10) allow start animation button to work again 
      }
    })();

  } else {
    console.log("Wait..."); // inactivate button
  }

  started = 1;
}
<div id="output" style="margin: 40px; font-size:130px"></div>
<div style="margin: 40px;">
  <button id="on" onclick="animator();">Start Animation</button>
</div>
<div style="margin: 40px;">
  <button id="off">Stop Animation</button>
</div>

Upvotes: 2

Views: 6176

Answers (2)

Jon Swanson
Jon Swanson

Reputation: 102

I'd probably use setInterval/clearInterval outside your interval function. You definitely want recurring intervals instead of single timeouts when you think about it.

So basically:

var something;

function start() {
  something = setInterval(interval, 1000);
}

function interval() {
  //animation code
}

function stop() {
  clearInterval(something);
}

Upvotes: 2

Fresheyeball
Fresheyeball

Reputation: 30015

You can easily solve this with state. Simply add a variable to your code called

  var isRunning = false;

which it to true when you start the animation, and false to stop the animation. Then inside your iterator function, check to see if isRunning is false. If isRunning === false, you don't call the next setTimeout, hence stopping the animation.

Upvotes: 3

Related Questions