Reputation: 833
I have the following piece of code:
for(var i=0;i<searchParamLength;i++)
{
(function(i){
url = "https://www.googleapis.com/customsearch/v1?q=" + searchParam[i] + "&cx=005894674626506192190:j1zrf-as6vg&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM&dateRestrict=" + date_length;
arrXhr[i] = new XMLHttpRequest();
arrXhr[i].open("GET", url, true);
arrXhr[i].onreadystatechange = function(){
var totalResults = 0;
if (arrXhr[i].readyState === 4 && arrXhr[i].status == 200)
{
totalResults = JSON.parse(arrXhr[i].responseText).searchInformation.totalResults;
console.log("Variable I: " + i + "Total results:" + totalResults);
totalResultsArr.push(totalResults);
}
};
arrXhr[i].send(null);
})(i);
}
Take a look inside my loop where I have a console.log(). I was experiencing some strange behavior in my code which is why I decided to check if the loop is behaving as expected. Indeed, take a look at the image below. The loop is executing in a strange way. It is first executing i=1 and then i=6 and then i=2, etc.
I have been researching on SO and I saw the following question but it didn't help me solve my problem. Anyone has any clue why is this happening?
Upvotes: 2
Views: 71
Reputation: 23768
JS moves on after sending the request and the onreadystatechange
even occurs when you get a response. The time taken to receive response may vary by the status of the connection, server processing time, server load etc. So the order of response is not necessarily be the order of request.
You can make a synchronous call alternatively. This is decided by the third argument of xhr.open
arrXhr[i].open("GET", url, false);
The procedure is slightly different in this case.
Here is a tutorial.
Upvotes: 1
Reputation: 32192
The requests are asynchronous. There's no guarantee that they will complete in the order you've made them in - that's why you're not seeing contiguous values for i
in the callback.
Upvotes: 4