2

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?

enter image description here

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Note that synchronous requests are in the process of being removed from the spec. Chrome already logs a warning, not sure about other browsers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.