Reputation: 187
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?
Upvotes: 1
Views: 136
Reputation: 5561
Valid doesn't increase because while cycle goes non-stop and overloads cpu immediately.
You need to call test after the timeout. Check:
var valid = 0;
function test() {
console.log(valid);
valid++;
if(valid < 5){
setTimeout(test, 1000*valid);
}
}
test();
Upvotes: 3
Reputation: 2255
The issue here is that the while loop must run to completion before any of the timeouts can run. That is, valid
will not be incremented until a second has passed and there is no other code running, but that will never happen because the while loop will still be running...
You need to schedule the following timeout inside the test function.
Upvotes: 0
Reputation: 554
The valid variable must be global, so try this
var valid = 0;
function test(i) {
return function() {
console.log(i);
window.valid++;
}
}
while (valid < 5) {
setTimeout(test(valid), 1000*valid);
}
Upvotes: 0