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?
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?
Share Improve this question asked Apr 23, 2012 at 7:53 JustinJustin 45.3k81 gold badges213 silver badges310 bronze badges3 Answers
Reset to default 6The 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 still unsure about the browser's capabilities in queueing the requests, you could try something like this:
var count = 0; // Number of functions being called
var funcArray = []; // Array of functions waiting
var MAX_REQUESTS = 5; // Max requests
var CALL_WAIT = 100; // 100ms
function call()
{
// Check if count doesn't exceeds or if there aren't any functions to call
if(count >= MAX_REQUESTS || funcArray.length == 0)
// Call call() after 100ms
setTimeout(function() { call() }, CALL_WAIT);
count++; // Add request to the counter
var func = funcArray.pop();
$.ajax(..., function(data)
{
func(data);
// .......
count--; // Substract request to the counter
});
}
$(function()
{
call(); // First call to start polling. It will call itself each 100ms
});
$(function()
{
$("div.server").each(function() {
funcArray.push(function(data)
{
alert(data);
});
});
});
You may have to tweak it for your needs.