Deferred Example 4

The fourth is the same as the third except there's now two workers that are both working to empty the queue meaning there are two requests going at any time until the queue is empty and once the final request is complete, it triggers a deferred

by someprimetime

JavaScript

var urls = [];

//Make a bunch of URLs, use delay= to make them take time to load.
for (var i = 0; i < 10; i++) {
    var n = Math.floor(Math.random() * 5);
    urls.push("http://jsfiddle.net/echo/jsonp/?delay=" + n + "&data=" + i);
}

var index = 0;

function worker(id) {
    var alldone = $.Deferred();

    //Do the next piece of work to be done.
    //This can be starting a new AJAX request or triggering the
    //final "alldone" deferred.

    function next() {
        if (index >= urls.length) {
            log(id + ": Finished my work");
            alldone.resolve();
            return;
        }

        var i = index++;

        log(id + ": Starting number " + i);
        $.ajax({
            url: urls[i],
            dataType: "jsonp",
            success: function() {
                log(id + ": Finished number " + i);
            }
        }).done(next);
    }

    //Start the first one
    next();

    return alldone;
}

$.when(worker("A"), worker("B")).done(function() {
    log("Last one finished!");
});





function log(msg) {
    $("<div>", {
        text: msg
    }).appendTo("body");
}