Alternatives to Synchronous JSON call

I am working on the Twitch app challenge and I ran through the problem where the loop traversing the list of channels couldn’t properly get the respective data for each channel.

 var channels = [ "ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb",  "noobs2ninjas" ];

I was using this code

  for (let i = 0; i <= channels.length - 1; i++) {
       $.getJSON("https://wind-bow.glitch.me/twitch-api/users/" + channels[i], function (data) {
                $("#"+channels[i]).html(data);        //the div IDs where the JSON data will be displayed are named after the channel 
 });

The above approach didn’t work due to the time taken by getJSON() to gather data from the stream which was causing issues. I found a solution for it, which I don’t quite understand well but apparently it is delivering the required result. Turns out, I can add ajaxSetup() and put async as false and from there everything just works.

  for (let i = 0; i <= channels.length - 1; i++) {
       $.getJSON("https://wind-bow.glitch.me/twitch-api/users/" + channels[i], function (data) {
            $.ajaxSetup({
              async: false
            }); 
            $("#"+channels[i]).html(data); 
 });

I’m getting the desired output but here is the problem. I can see a visible delay for a few moments when before the divs load the JSON data. The page looks as if it is frozen. I’m curious to know if there is some other method to execute the same thing, because it is likely that with bigger amount of data the delay will consequently get bigger. Furthermore, I plan to add the feature to auto refresh the online-offline status of channels every few seconds so frequent JSON calls is bound to slow the page. Please help.
Also, I merely copy-pasted the code from a stack overflow answer for getting a synchronous output using JSON. Can anyone explain why was there an issue in the first place and how the ajaxSetup() function takes care of it?


Here is the link to the pen.

Thanks. It totally worked. Now when I see it it looks so simple but I never could’ve done without your help. Once again, thanks a ton :grinning: