This is a pretty common problem that we all run into at some point in our web development career. It’s one of those things that’s confusing to understand at first, but once you get it you’re going to sail through your other projects. I’ve written a post on a similar issue here:
This isn’t your exact issue, but it’s close. Basically, your loop is running faster than the AJAX calls can go out. By the time your first AJAX call gets its response, the loop has run and the variable i is not the same as it was when the AJAX call started. While it’s not the easiest or the prettiest solution, this may be the easiest to learn right now:
for (i = 0; i < channel.length; i++) {
var currentChannel = channel[i]; //Define your channel here
$.ajax({
url: 'https://api.twitch.tv/kraken/streams/' + currentChannel,
headers: {
"Client-ID": "gdtobx6xx8k4rcsmo6aq26braesqelq"
},
error: streamError(),
success: function(data) {
//do stuff here
//move all DOM manipulation here
}
});
};
The best solution right now is to use promises, which will clean up your code and eliminate the need for global variables. Check this video out Are you bad, good, better or best with Async JS? JS Tutorial: Callbacks, Promises, Generators
I actually apologize here, I can’t give you as detailed of an answer as I’d like at the moment, but I’m hoping this can get you headed in the right direction. Let me know if you have any particular questions and I’ll see if I can answer it when I’m able to focus later.