Process batches of async actions...

http://benalman.com/ http://benalman.com/projects/jquery-message-queuing-plugin/

by secretgspot

HTML

<h1>Batch-processing a queue asynchronously</h1>
<p>For a much sexier interface, error handling, and a whole bunch more, check out the <a href="http://benalman.com/projects/jquery-message-queuing-plugin/" target="_top">jQuery Message Queuing</a> plugin and the <a href="http://benalman.com/code/projects/jquery-message-queuing/examples/ajax/" target="_top">Serial AJAX example</a>.</p>

CSS

h1 { font-size: 120%; font-weight: 700; }
h1, p { margin-bottom: 0.6em; }

JavaScript

function process( q, num, fn, done ) {
    // remove a batch of items from the queue
    var items = q.splice(0, num),
        count = items.length;

    // no more items?
    if ( !count ) {
        // exec done callback if specified
        done && done();
        // quit
        return;
    }

    // loop over each item
    for ( var i = 0; i < count; i++ ) {
        // call callback, passing item and
        // a "done" callback
        fn(items[i], function() {
            // when done, decrement counter and
            // if counter is 0, process next batch
            --count || process(q, num, fn, done);
        });
    }
}

// sample logging function
function log( msg ) {
    $('body').append(msg + '<br/>');
}

// create queue
var queue = [];
for ( var i = 0; i < 20; i++ ) { queue.push(i); }

// a per-item action
function doEach( item, done ) {
    log('starting ' + item + '...');
    // (simulating ajax)
    setTimeout(function(){
        log('completed ' + item + '!');
        done();
    }, Math.random() * 1000);
}

// an all-done action
function doDone() {
    log('all done!');
}

// start processing queue!
process(queue, 5, doEach, doDone);