1

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?

0

3 Answers 3

3

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Also, if you need to return a value, as it looks like you might be trying to do, try using a callback style, as this SO answer explains a bit: stackoverflow.com/a/7142064/1981678
You made my day really! Now I would like to understand how this code works. Is this a recursive function? Thank you very much for your help you solved a really big problem :)
Yep, it executes itself, so it's recursive.
0

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);
}

2 Comments

Thank you but it's crashing
Your statement is technically correct, but the variable is already global. The reference to valid inside test() was already referring to the global variable.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.