I spent a lot of this time on this problem and finally I can show it in an easy to read code in jsfiddle: http://jsfiddle.net/Lb0g25ae/
function test(i) {
return function() {
console.log(i);
//I need to increase valid here because this is where the script will choose wheter to increase or not (continue looping) valid depending on some conditions
}
}
var valid = 0;
while (valid < 5) {
setTimeout(test(valid), 1000*valid);
valid++;
}
And I need it to be
function test(i) {
return function() {
console.log(i);
valid++;
}
}
var valid = 0;
while (valid < 5) {
setTimeout(test(valid), 1000*valid);
}
But this way the loop won't stop, because valid is not being increased, this will produce an infinite loop and a crash. Someone can point me in the right direction?