Possible Duplicate:
Queue AJAX calls
I have a list of id:
var ids = [3738, 75995, 927, ... ]; // length is about 2000
I'd like to request the url http://xx/ + id
with $.getJSON
, like:
ids.forEach(function(id, index){
$.getJSON('http://xx/' + id, function(data){
// store the data in another array.
});
});
However, this will make too much requests in one time, making the browser blocking for a while, so my question is, how could I limit the number of concurrent ajax request in jQuery? for example, I send 10 request and when each of them got the response I send another request.
shift()
or pop()
the ids off of the array as you start the requests. Start by firing off 10 requests. Then in the complete()
handler for your ajax call, check for an array length. If it's greater than 0, setTimeout
for a few hundred milliseconds (to free up the browser a bit) and then shift or pop off another ID and fire another request.
var $queue = $({});
ids.forEach(function(id, index) {
$queue.queue("ajaxQueue", function( next ) {
$.getJSON('http://xx/' + id, function(data){
// store the data in another array.
next();
});
});
});
$queue.queue("ajaxQueue", function() {
// everything is saved
});
$queue.dequeue("ajaxQueue");
jQuery docs:
jQuery.queue
jQuery.dequeue
SO:
What are queues in jQuery?
Also:
The solution should be how can I make the backend handle multiple ids. – epascarello
##Ten request at the time: Have some issues!
var $queue = $({}),
handler;
ids.forEach(function(id, index) {
if ( !(index % 10) && handler ) {
$queue.queue("ajaxQueue", handler);
}
handler = (function(prev) {
return function( next ) {
prev();
$.getJSON('http://xx/' + id, function(data){
// store the data in another array.
});
if ( next ) {
next();
}
}
})(handler);
});
$queue.queue("ajaxQueue", function() {
// everything is saved
});
$queue.dequeue("ajaxQueue");
x % y
(index % 10) => Math.floor(index/10)*10 === index;
!(index % 10) => Math.floor(index/10)*10 !== index;
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