Mostafa 36a2
Mostafa 36a2

Reputation: 177

Strange behaviour Function within a loop

I can't understand what is happening inside this code, it prints 13 only.

/*jshint loopfunc: true */
for(var i=0;i<13;i++)
    setTimeout(function(){console.log(i)},10); 

The output is

13
13
...[10 times more]
13

How can I print 0,1,2,...,12 with lambdas like how I wish to do?

Upvotes: 0

Views: 47

Answers (2)

codebox
codebox

Reputation: 20254

This should work:

for(var i=0;i<13;i++) {
    (function(j){
        setTimeout(function(){console.log(j)},10); 
    }(i))
} 

in your original code the i variable gets incremented all the way up to 13 and then gets used by each of the console.log statements. To fix the problem you can create an anonymous function and pass the i variable to it on each iteration of the loop, this effectively takes a snapshot of the value of i at the time the function was called so console.log prints out the desired values.

Upvotes: 2

udidu
udidu

Reputation: 8588

Try this:

for(var i=0;i<13;i++)
    setTimeout(function(index){console.log(index)}.bind(this, i),10);

Upvotes: 0

Related Questions