Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking out of setTimeout loop

I'm having some trouble breaking out of a setTimeout loop.

for (var i = 0; i < 75; i++) {
  setTimeout(function (i) {
    return function () {
      console.log("turn no. " + i);
      if (table.game.playerWon) {
        console.log('Player won');
        // I want to stop the loop now
        // i = 75; didn't work
      }
    };
  }(i), 100 * i);
}

I've read like 100 setTimeout related posts, but can't figure this one out.

edit:

Let me clarify a bit when I'm trying to accomplish.

My game has 75 turns, each turn should take about 500ms, during that turn I want to check if a condition is met and announce that the player won, after the player has won there is no need to continue the rest of the turns.

like image 698
Martijn Avatar asked Jan 20 '14 17:01

Martijn


People also ask

How do I stop a setTimeout loop?

To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.

Can you cancel a setTimeout?

The global clearTimeout() method cancels a timeout previously established by calling setTimeout() .

How do I destroy setTimeout?

You can use clearTimeout() to do that. You'll need to keep the return value from setTimeout() in a variable to pass to clearTimeout() .

Does setTimeout run forever?

The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead. Use the clearTimeout() method to prevent the function from starting.


1 Answers

Instead of setting all those timers, create one continuous timer with setInterval:

var counter = 0;

var timer = setInterval(function () {

    console.log("turn no. " + counter);

    if (table.game.playerWon) {
        console.log('Player won');
    }

    if (counter >= 75 || table.game.playerWon) {
        clearInterval(timer);
    }

    counter++;

}, 100);

If your turns should take 500ms, change that last 100 to 500.

like image 164
Joseph Silber Avatar answered Sep 30 '22 18:09

Joseph Silber