Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery request a list of url while limit the max number of concurrent request [duplicate]

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.

like image 382
wong2 Avatar asked Nov 03 '22 12:11

wong2


2 Answers

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.

like image 88
Randy Hunt Avatar answered Nov 09 '22 12:11

Randy Hunt


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;
like image 31
Andreas Louv Avatar answered Nov 09 '22 11:11

Andreas Louv