I am running the forEach loop. I want it create the script tag and run the callback function (myCallbackFunction). However, the forEach Loop only runs on the first function (createURL), when myCallbackFunction runs, it’s no longer in the forEach loop and so I lose ‘name’. If you bring up the console, you’ll see my problem.
Is there a way to loop through both functions for each of the userNames? Or any suggestions on how to use callback without calling another function? I am trying to do this in straight javascript without jQuery. Trying to learn the basics before piling on the libraries.
var userNames = [“freecodecamp”, “OgamingSC2”, “cretetion”, “storbeck”, “habathcx”, “RobotCaleb”, “ESL_SC2”];
function myFunction () {
userNames.forEach(createUrl);
}
function createUrl (name) {
tempscript = document.createElement(“script”);
tempscript.type = “text/javascript”;
tempscript.id = “tempscript”;
tempscript.src = “https://wind-bow.gomix.me/twitch-api/streams/” + name + “?callback=myCallbackFunction”;
document.body.appendChild(tempscript);
console.log(document.getElementById(“tempscript”).src);
document.body.removeChild(tempscript);
}
function myCallbackFunction(data) {
console.log("name = " + name);
console.log("data.stream is: " + data.stream);
if (data.stream == null) {
var status = "Offline";
var h = document.createElement("div");
h.innerHTML = '<div class="row"><div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"><div class="thumbnail"><p>' + name + '</p>' + ' ' + status + '</div></div></div>';
document.getElementById("content").appendChild(h);
} else {
var status= "Online";
var desc = data.stream.game;
var onlineUrl = data.stream.channel.url;
var h = document.createElement("div");
h.innerHTML = '<div class="row"><div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"><div class="thumbnail"><p>' + name + '</p>' + ' ' + status + ' ' + desc +'</div></div></div>';
document.getElementById("content").appendChild(h);
}
}