Not a bug, just wrap the scope that you want to use in a function call:

for (var i=0; i < array.length; i++) (function(i){
    var item = array[i];
    setTimeout(function() {
        console.log(item);
    }, 1000*i);
})(i);

Or use Array's forEach method which does this more compactly:

array.forEach(function(item, i){
    setTimeout(function(item) {
        console.log(item);
    }, 1000*i);
}

It may not be intuitive (it's certainly confused me!), but if it worked the 
way you suggest, there's be no way to read the current, completed iteration 
of the for loop, instead of the closure'd value.

I wouldn't use the additional arguments functionality of 
setInterval/setTimeout. If you do need it in the future, use a small 
function closure (as above) or the .bind() method instead:

setTimeout(myfunc.bind(null, firstargument));

Or, use something else entirely:

var i = 0;
(function next(){
    var item = items[i++];
    if(item===undefined) return void done();
    console.log(item);
    setTimeout(next, 1000);
})();

Or:

function next(i){
    var item = items[i];
    if(item===undefined) return void done();
    console.log(item);
    next(i+1);
}
next(0);

On Thursday, July 11, 2013 7:42:25 AM UTC-7, Jean-Michel Hiver wrote:
>
> Funny how I scratched my head for an hour or so and found the answer 
> afterwards:
>
> for (var i=0; i < array.length; i++) {
>     var item = array[i];
>     setTimeout(function(item) {
>         console.log(item);
>     }, 1000*i, *item*);
> }
>
> Still I think the way closures works is a bug...
>

-- 
-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to