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.
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.
The global clearTimeout() method cancels a timeout previously established by calling 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() .
The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead. Use the clearTimeout() method to prevent the function from starting.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With