-1

my console.log(url) return the same thing every time but when i console it outside the json call, everything work just fine. why is that and how i can fix it? the for loop is counting before the Json make the call. for example when i console the i inside the Json it returns the number 8, 8 times but if i console the i outside de json but inside the for loop it returns 0 to 7

$(document).ready(function(){ 
    var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx","RobotCaleb","noobs2ninjas"]; 
    for(var i = 0;i<channels.length;i++){ 
        var url='https://api.twitch.tv/kraken/channels/'+channels[i]+'?client_id=pd57d4ktf8rjarn9q3qgtv4owbr5q0'; 
        console.log(url);
        $.getJSON(url,function(data){
            console.log(url);    
        });
 }});
  • Can you please make it clear? It is working as expected. What are you expecting? – Praveen Kumar Purushothaman Jan 06 '17 at 01:29
  • I suspect this could be considered a duplicate of http://stackoverflow.com/questions/111102/how-do-javascript-closures-work/111111#111111 – Blorgbeard Jan 06 '17 at 01:36
  • the for loop is counting before the Json make the call. for example when i console the i inside the Json it returns the number 8, 8 times but if i console the i outside de json but inside the for loop it returns 0 to 7 – Jorge ZAMUDIO Jan 06 '17 at 01:42
  • http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Pang Jan 06 '17 at 01:43
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Louis Jan 09 '17 at 00:21

1 Answers1

0

The two links in the comments give reasons for why this is happening but the specific reason you are seeing this is because your getJSON call is asynchronous. Your loop will complete before the callback that you pass to getJSON is executed. That is why your console.log outside of the callback is what you expect but the one inside the callback logs out the same end state 8 times.

The following snippet hopefully will give you a clearer indication of what is happening. Notice how the "In loop" lines all happen before any of the "In callback" lines.

for(var i = 0; i < 5; i++) {
  console.log("In loop", i);
  
  // Simulate an asynchronous request
  setTimeout(function() {
    /*
      By the time this executes, i has been incremented
      to 5 so the loop is finished.
    */
    console.log("In callback", i);
  }, 1);
}
rdubya
  • 2,916
  • 1
  • 16
  • 20