Amr Ayoub Amr Ayoub - 1 month ago 5
Javascript Question

Javascript AJAX pending request

I'm trying to create a function which when You send a http(s) request. If there is 5 or more ongoing requests, you have to wait until one
of them is completed then you can process next request.
i have done this so far

function makerequest ("/routeplanner/data","GET",sucess,error)
{


var xmlHttp = new XMLhttpRequest();


var count =0;

xmlHttp.onreadystatechange = function() {
if (xmlHttp.readystate ==4 && xmlHttp.statue ==200) {
success (xmlHttp.responseText);}

else if (xmlHttp.status !=200 &&count !=3){
count++;
xmlHttp.open(method,url,true);

else if (count ==3){
error("you have reached the maximum number of tries")
}
}
xmlHttp.open("GET","/routeplanner/data",true);

xmlHttp.send(null)
}


any idea how that can be done in pure JS.

Answer

Syntax issues with your example code aside, you need to keep track of the count outside of the function that does the check.

// Store this outside of the function
var activeRequests = 0;
var maximumRequests = 5;

function makeRequest(...) {
  // Quit early if the maximum has been exceeded
  if (activeRequests >= maximumRequests) {
    error('too many requests');
    return;
  }
  ...
  xmlHttp.onreadystatechange = function () {
    ...
    // Decrease the number of active requests when one is completed
    --activeRequests;
    ...
  };
  ...
  // Increase the number of active requests when one starts
  ++activeRequests;
  ...
}