Breaking out of setTimeout loop
Problem
I'm having some trouble breaking out of a Settimeout Loop.
for (var i = 0; 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.
Problem courtesy of: Martijn
Solution
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
.
Solution courtesy of: Joseph Silber
Discussion
View additional discussion.