Basic sequencing multiple asynchronous operations
This crude example shows the underlying principles of sequencing multiple asynchronous operations.
It even uses an asynchronous timer
HTML
<button>Start</button>
<div id="container"></div>
CSS
#container > div {
display:none;
height:25px;
text-align:center;
border:2px solid Red;
}
JavaScript
$(document).ready(function () {
$("button").click(function () {
//take a reference to container for ease of access
var $container = $("#container");
//create 10 hidden boxes ready for animation
for (var i = 1; i <= 10; i++) {
$("<div>").html("Box " + i).appendTo($container);
}
//take a reference to child div's for ease of access
var $div = $container.children("div");
//initialize loop counter
var count = 0, maxCount = $div.size();
function doNext() {
if (count >= maxCount) return; //break loop after 10
oneStart($div.eq(count++)); //call fn to kick an animation off
window.setTimeout(doNext, 1000); //loop again after 1,000mS
}
doNext(); //start the animation sequence
//this is called to start eaach asyn animation
function oneStart($target) {
//start animation, set async callback handler
$target.html($target.html() + " started "); //update status
$target.fadeIn(5000, oneDone);
}
//this is called asynchronously when each animation completes
function oneDone() {
$(this).html($(this).html() + "finished!!"); //update status
}
});
});