charly rl
charly rl

Reputation: 885

jquery $.each vs for loop (with async content)

What is the main difference between:

    var test=[5,6,7,8,9];
    $.each(test, function (i, num) {
        setTimeout(function(){console.log('i: '+i+'  '+num)},500);
    });
    for (var j = 0; j < test.length; j++) {
        setTimeout(function(){console.log('j: '+j+'  '+test[j])},500);
    }

First loop outputs:

i: 0  5
i: 1  6
i: 2  7
i: 3  8
i: 4  9

Second loop outputs:

5 times 'j: 5 undefined'

I understand why the second loop does this, but not why $.each works 'as expected'

Thanks!

Upvotes: 1

Views: 71

Answers (1)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

In the first snippet's behind the scene, for every iteration the call back that you have supplied will be called. That means, internally it will create a scope per iteration. That eventually becomes a cloure.

But in the second snippet. The initial scope will be used while the timeout's call back got triggered. So it is displaying that output. And you can make it work by using the following code,

for (var j = 0;j<test.length-1;j++) {
 var scope = function(i) { 
  setTimeout(function(){console.log('j: '+i+'  '+test[i])},500);
 };
 scope(j);
}

Upvotes: 1

Related Questions