rurounisuikoden
rurounisuikoden

Reputation: 269

Use Javascript to send multiple requests to server until server returns 200

I have created a html page which the user views when they are waiting for another application to restart. I have created a javascript script which makes multiple requests to the application until the application returns 200. However, when i try to open my html page, the browser simply crashes. Can anyone see whats wrong with my code:

var responseStatus = 404;
var numberOfTries = 0;
var request = new XMLHttpRequest(); 
while(responseStatus != 200){
    console.log("Checking if restart has completed. Attempt number: " + numberOfTries);
    request.open('GET', 'applicationurl', true);
    request.onreadystatechange = function(){
        if (request.readyState === 4){
            console.log("Request Status: " + request.status);
            responseStatus = request.status;
            console.log("Response Status: " + request.status);
            if (request.status != 200) {  
                numberOfTries++;
                console.log("Restart has not yet completed! NumberOfTries: " + numberOfTries);
            }  
        }
    };
    request.send();
}
console.log("Server has successfully restarted");

Upvotes: 2

Views: 3225

Answers (3)

Paul
Paul

Reputation: 36339

The best way to do this (in my opinion) is to actually combine @serge1peshcoff's two options. Write the call as a function that calls itself when the response fails, and set a timeout when doing so. For most purposes, you don't want to send another request immediately after the previous one, you want to wait at least a second or five to prevent spamming the server (you've also given no indication of how many clients you expect. What's bad for your browser is potentially horrible for the server, which may be handling requests even before your web app is fully up and returning 200).

Also, setTimeout is a better approach than setInterval, as you explicitly reset it on each round trip.

Borrowing from @serge:

function tryRequest(numTries) {
  var responseStatus = 404;
  var request = new XMLHttpRequest(); 
  numTries = numTries || 0;

  console.log("Checking if restart has completed. Attempt number: " + numAttempts);
  request.open('GET', 'applicationurl', true);
  request.onreadystatechange = function(){
      numTries++

      if (request.readyState === 4){
          console.log("Request Status: " + request.status);
          responseStatus = request.status;
          console.log("Response Status: " + request.status);
          if (request.status != 200) {  
              console.log("Restart has not yet completed! NumberOfTries: " + this.attempts);
              setTimeout(tryRequest.bind(null, numTries), 5000); // five seconds
          }  
      }
  };
  request.send();

  console.log("Server has successfully restarted");
}
tryRequest();

Upvotes: 3

serge1peshcoff
serge1peshcoff

Reputation: 4660

Your approach sends a multiple requests, however it doesn't wait for them to respond.

Here is how it works:

  • an XMLHttpRequest is created
  • a callback and a data is assigned to it
  • this object is sent to server
  • then the while loop ends and runs again, not waiting for the callback to be run

As a result, a lot of XMLHttpRequest objects are created and a lot of requests are run simultaneously, which is not what you want.

You can do this 2 ways:

  • wrapping it into a function and call it when it fails (preferrable);
  • setting some interval to wait for response

1st approach:

function tryRequest(numAttempts) {
  var responseStatus = 404;
  var request = new XMLHttpRequest(); 

  console.log("Checking if restart has completed. Attempt number: " + numAttempts);
  request.open('GET', 'applicationurl', true);
  request.onreadystatechange = function(){
      if (request.readyState === 4){
          console.log("Request Status: " + request.status);
          responseStatus = request.status;
          console.log("Response Status: " + request.status);
          if (request.status != 200) {  
              console.log("Restart has not yet completed! NumberOfTries: " + numAttempts);
              tryRequest(numAttempts + 1)
          }  
      }
  };
  request.send();

  console.log("Server has successfully restarted");
}
tryRequest(0);

2nd approach:

var responseStatus = 404;
var numberOfTries = 0;
var request = new XMLHttpRequest();
var interval = setInterval(tryRequest, 1000)

function tryRequest() {
  console.log("Checking if restart has completed. Attempt number: " + numberOfTries);
  request.open('GET', 'applicationurl', true);
  request.onreadystatechange = function(){
      if (request.readyState === 4){
          console.log("Request Status: " + request.status);
          responseStatus = request.status;
          console.log("Response Status: " + request.status);
          if (request.status != 200) {
              numberOfTries++;
              console.log("Restart has not yet completed! NumberOfTries: " + numberOfTries);
          } else {
              clearInterval(interval);
              console.log("Server has successfully restarted");
          }
      }
  };
  request.send();
  }

}

(disclaimer: I didn't test both of then)

Upvotes: 1

Veer
Veer

Reputation: 6936

You can use Code like

var responseStatus = 404;
var numberOfTries = 0;
function check(){
        var request = new XMLHttpRequest(); 
        console.log("Checking if restart has completed. Attempt number: " + numberOfTries);
        request.open('GET', 'applicationurl', true);
        request.onreadystatechange = function(){
            if (request.readyState === 4){
               console.log("Request Status: " + request.status);
               responseStatus = request.status;
               console.log("Response Status: " + request.status);
               if (request.status != 200) {  
                  numberOfTries++;
                  console.log("Restart has not yet completed! NumberOfTries: " + numberOfTries);
                   var tmp = setTimeout(function(){ check() },5000 ); // check after 5 second
               }  elseif (request.status == 200) {  
                    console.log("Server has successfully restarted");
               }
            }
        };
        request.send();

  }

// Call first time

check();

Upvotes: 0

Related Questions