Deferred Example 2

Second is how you can take a list of URLs and download them one at a time, then do something when that's finished:

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() * 2);
    urls.push("http://jsfiddle.net/echo/jsonp/?delay=" + n + "&data=" + i);
}

var index = 0;
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) {
        alldone.resolve();
        return;
    }
    
    var i = index++;

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

alldone.done(function() {
    log("Last one finished!");
});

//Start the first one
next();





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