Jumperz Ko
Jumperz Ko

Reputation: 401

JavaScript for loop different order

Can anyone tell me why I get different order everytime the code loops? I'm very new to JavaScript and I know the code isn't very neat.

<html>
<body>
<div id="status">

<br>
</div>
<script>
LoopThis()

function LoopThis(){


document.getElementById("status").innerHTML = "Status - Name: <br>"
var USERLIST = ["amd","danielfromsl","skyrimfus","tyler1","andymilonakis","OMGchad","Russ_Money","h3h3productions"]
var i, len;

for (i = 0, len = USERLIST.length; i < len; i++){

USERCHECK = USERLIST[i]

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        JSONDOC = this.responseText;
        last = JSONDOC.split('"mature":')
        last = last[1]
        last = last.split(",")
        isonline = last[0]
        streamtitle = last[1].split('"status":')
        streamtitle = streamtitle[1]
        realuser = last[3].split('"display_name":')
        realuser = realuser[1]
        realuser = realuser.split('"')
        realuser = realuser[1]
        url = last[15].split('"url":')
        url = url[1]
        url = url.split('"')
        url = url[1]
     if (isonline == "true") {
        //alert(realuser+" is streaming! Title:"+streamtitle)
        document.getElementById("status").innerHTML += "<font color='0x00FF00'>Online</font> - "+"<a href='"+url+"'>"+realuser+"</a><br>"
      } else { 
        //alert(realuser+" is offline!")
        document.getElementById("status").innerHTML += "<font color='red'>Offline</font> - "+realuser+"<br>"
     }



    }
  };
  xhttp.open("GET", "https://api.twitch.tv/kraken/channels/"+USERCHECK+"?client_id=Sky", true);
  xhttp.send();

}
}

setInterval(LoopThis,5000);
</script>

</body>
</html>

Upvotes: 0

Views: 66

Answers (1)

jpuntd
jpuntd

Reputation: 902

You use a for loop to loop through the list of users in a predefined order. But inside the loop you make an asynchronous XMLHttpRequest and you give it a function that will run when you receive a response for that request. The function you have attached to the xhttp.onreadystatechange event will run when a response is received.

The responses can be received in a different order everytime the script is run and that's why the different xhttp.onreadystatechange events will fire in a different order.

Upvotes: 1

Related Questions