Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Limit The Number Of Simultaneous AJAX Requests

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?

like image 311
Justin Avatar asked Apr 23 '12 07:04

Justin


People also ask

Can we execute run multiple AJAX requests simultaneously in jquery?

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.

How many AJAX requests at once?

It is worth noting that browsers can generally only handle 6 ajax requests at a time, this may catch you out.

How do you send AJAX request every 5 seconds?

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.


2 Answers

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.

like image 103
ThiefMaster Avatar answered Sep 17 '22 01:09

ThiefMaster


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.

like image 45
Ates Goral Avatar answered Sep 18 '22 01:09

Ates Goral