Amr Ayoub Amr Ayoub - 3 years ago 199
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){

else if (count ==3){
error("you have reached the maximum number of tries")


any idea how that can be done in pure JS.

Answer Source

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');
  xmlHttp.onreadystatechange = function () {
    // Decrease the number of active requests when one is completed
  // Increase the number of active requests when one starts
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download