so I have a series of AJAX events I would like to fire, but I want to limit the number of simultaneous requests to 5, and queue up the rest. So for example, I have the following:
$("div.server").each(function() {
$.ajax(....);
});
So there may be 100 divs with the class server
, but I want to only run 5 requests at any given time. Once a request finishes it should proceed to the next.
What is the best way to do this?
There is a requirement to make multiple AJAX calls parallelly to fetch the required data and each successive call depends on the data fetched in its prior call. Since AJAX is asynchronous, one cannot control the order of the calls to be executed.
It is worth noting that browsers can generally only handle 6 ajax requests at a time, this may catch you out.
Creating a function that calls the AJAX request and using this function in setInterval() and set Interval for 5 sec. Now the function executes every 5 seconds and fetches new data from the server. It repeatedly executes the function even when the previous AJAX request is not successfully executed and return.
The best way to do this is letting the browser deal with it. Usually browsers already have a per-host connection limit so they will automatically queue connections if there are too many.
However, I'd consider changing the API so it takes date from multiple elements and also returns data for multiple elements - i.e. reducing the overall count of HTTP requests necessary.
Push all request arguments to a queue with a function called queueRequest
and call checkQueue
. checkQueue
checks to see if there are items in the queue and if the number of active requests is less than 5. If these conditions are met, it pops a request from the queue and turns it into a real AJAX request. Then it attaches a done
handler to the request that decreases the active request count and calls checkQueue
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With