Breaking out of setTimeout loop
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
.
You shouldn't use a for loop , just a recursive setTimeout
- Read about the recursive setTimeout pattern
- When saying
about 500ms
, I assume it doesn't have to be so accurate - setInterval is harmful and most developers are probably not aware of it.
setInterval
does not fit for so many things:
- If an error occurs you cannot stop the train.
- If you need different execution time steps.
- If you need to pass data inside the chain.
- If you need to do something asynchronous.
- And the worse thing - SETINTERVAL DOES NOT GUARANTEE EXECUTION
- So use it only if you know what you are doing!
Solution:
var func = function(i){
return function(){
if (i >= 75) return;
console.log("turn no. " + i);
if(table.game.playerWon) {
console.log('Player won');
} else {
setTimeout(func(++i), 500);
}
}
}
setTimeout(func(0), 500);
You can run it in node.js
if you want to check how it works:
var winTurn = 10;
var func = function(i){
return function(){
if (i >= 75) return;
console.log("turn no. " + i);
if(i === winTurn) {
console.log('Player won');
} else {
setTimeout(func(++i), 50);
}
}
}
setTimeout(func(1), 50);
I think would be better you use a setInterval instead of setTimeout.
And for clear both of them you assign them to a variable and then you clear the timeout with
var myVar = setTimeout(func, time);
var myVar2 = setInterval(func, time);
clearTimeout(myVar);
clearInterval(myVar2);