tags:

views:

102

answers:

2
+2  Q: 

How to count to 3?

+4  A: 
for (var i = 1; i <= 3; ++i) {
    setTimeout((function (x) {
        return function () { alert(x); }
    })(i), i * 1000);
}
deceze
Perhaps you could add some explanation as well?
rchern
@rchern I wouldn't mind, but this has been explained a [thousand times over](http://stackoverflow.com/questions/tagged/javascript+loops+closures) already and this question seems destined for quick closure (pun intended) as duplicate of one of these. Also, the OP seems to understand the problem, he was just looking for the syntax.
deceze
Why give half an answer then? If you know it is going to be closed? *shrugs*
rchern
@rchern Why not? Isn't half an answer better than no answer? *shrugs* :)
deceze
@deceze: But a full answer is still better than a half answer.
BrunoLM
@Bruno But a full answer seemed like a waste of time, since it won't serve anybody in the future, since the question is now closed. Sorry for providing half-assed help. The weather is bad, okay? ;o)
deceze
I don't understand answering a question you're voting to close as a dupe. Isn't it contradictory?
rchern
@rchern Closing is a long-term clean up/maintenance thing, it doesn't mean I can't also give the OP a direct answer which helps him immediately.
deceze
Thanks deceze :) That's correct, I didn't need an explanation of closures... I just forgot what syntax to use. I knew I could create one by creating an anonymous function and calling it immediately, but the part I was forgetting was that I needed to return a new function.
Mark
@everybody There you go. Awesome, -2 on a correct and accepted answer. Is there a badge for that? :o)
deceze
I think I solved this before by putting the closure around the `setTimeout` and without the return.. I was trying to put it inside the `setTimeout` this time and it wasn't working.
Mark
+4  A: 

That is a very common issue. With JS 1.7 this is easily solved using let keyword. To check browser version equivalency click here.

You can workaround this using closures. Create a scope for i and return the function for setTimeout.

for (var i = 1; i <= 3; ++i) {
    setTimeout((function(i) { /* i is now a parameter */
        return function () { /* this function is the one that will execute */
            alert(i); /* this `i` is not the same as the one used on the loop */
        }
    })(i), i * 1000);
}
BrunoLM