0

If I use .each() both console logs return the same value, but if I use for the second one returns only the array length, length of the array times. What's the difference between them? What am I missing?

    //for (var i = 0; i < streamers.length; i++) 
    $.each(streamers, function(i,data) {
        console.log(i);
        $.getJSON('https://api.twitch.tv/kraken/streams/' + data + '?callback=?', function(data) {
            console.log(i);
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ZygD
  • 22,092
  • 39
  • 79
  • 102
Atlas
  • 107
  • 2
  • 8

1 Answers1

0

With $.each you are creating a closure for each iteration in which i is not changed.

With a for loop, i is changed before the $.getJSON callback is executed, so it will show the last possible value (because $.getJSON is asynchronous).

4castle
  • 32,613
  • 11
  • 69
  • 106
  • Even if the the `GET` requests were instantaneous, `i` would still change before the callbacks. The *current code* has to finish running before the "async" code can run. – just.another.programmer Aug 06 '16 at 19:11
  • @just.another.programmer If it was instantaneous, it wouldn't be asynchronous. – 4castle Aug 06 '16 at 19:14
  • Yes and no. There would be no reason to, but if you wanted to, you could still execute it async. Async just means that the code does not run in order with where it is written. It runs at some unspecified "later time" when the thread is available. – just.another.programmer Aug 06 '16 at 19:39
  • @just.another.programmer Interesting, so you could use `setTimeout` with `0` delay, and it would still run at the end of the code. Useful! – 4castle Aug 06 '16 at 20:35
  • Yes, exactly. You don't even need to pass the `0`, just use `setTimeout(yourCode)` and it will eval after the entire current call finishes. – just.another.programmer Aug 07 '16 at 06:41