Twitch acts very buggy, despite no console errors being shown

Twitch acts very buggy, despite no console errors being shown


Hey guys, I’ve been working on the twitch project for the last few days and even though the code seems fine at this point, it acts very buggy. To be more precise, the API response should attach a span (online or offline) to each channel that is being called. However, no matter how many times I refresh the page, it almost always leaves out some of the channels, i.e. they don’t get the online or offline status attached to them. And it’s very random, because each time it’s a different set of channels that gets “ignored” by the API.

Kind of difficult to explain, but to see what I mean, go to my pen and refresh the page a few times:

I have since looked at some of the other projects and they seem to work fine, so there must be something with my code, but I can’t figure out what it is. There are no console errors.


I believe I see what is going wrong here:

You have two for loops that loop over the array with channel names. In the first loop you create the <p class="name <channel-name>"></p> too which you append “online” or “offline” in the second loop.

Since the ajax calls are asynchronous, it is possible that the <p class="name <channel-name>"></p> is not yet created at the moment that you try to append something to it.

EDIT: See @kevcomedia’s post for a solution.


You’re making two AJAX requests “in parallel” for each user, and you can’t predict which of the two request finishes first (the channel request or the stream request). If I understood your intent correctly, you want to request for stream data after channel data. In that case, you may want to embed the second request inside the first one, like so:

$.getJSON('channel/url', function(ata) {
  // ...

  $.getJSON('stream/url', function(data) {
    // ...

Also, consider using let instead of var in the for-loop, because you’re bound to get bugs with async code in for-loops if you used var (like in this case, the status might not show in the page)


Thank you Ben and Kev, works perfectly now! I forgot that timing is essential when working with asynchronous calls, I think I’ll remember this next time. The funny thing is that I initially nested the API calls like you suggested, but because the code was becoming unreadable (I was experimenting and there was a lot of useless code), I separated them into two for loops.

I appreciate the help guys! And I must say, it’s really rewarding to complete these freeCodeCamp projects and seeing them work.