0

First off: I am not using global variables. I'm just using them in this example to make things easier. I am actually attaching them to another object and not the window.

Here's what I'm trying to do:

window.i = 0;

while(window.i < 10){
setTimeout(function(){alert(window.i);}, 2000);

window.i++;
}

After two seconds I get ten alerts but they all say '10'. Is there a way to "convert" the variable into a unique variable in the timeout? So I can get alerts like 1, 2, 3, 4...

I can't use a string, it has to be a function. So nothing like this:

setTimeout('alert(i);', 2000);

Thanks!

1 Answer 1

1

You need to make a closure to "capture" each value of i. Otherwise, each timeout will be referencing the "final" value.

var i = 0;
var timeoutFunc = function(i){
    return function(){
        alert(i);
    };
};

while(i < 10){
    setTimeout(timeoutFunc(i), 2000);

    i++;
}
Sign up to request clarification or add additional context in comments.

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.