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?