A few months ago I was writing a little application where I was doing a lot of asynchronous calls in javascript and having to track their completion to do some other stuff, it resulted in this:
// Synchronizes asynchronous calls: sync(functions..., completionHandler)
var sync = function() {
var argLength = arguments.length - 1
, completed = 0
, callback = arguments[argLength]
for (var i = 0; i < argLength; i++) {
arguments[i](function() {
completed++;
(completed == argLength) && callback && callback();
});
}
};
It pretty much takes a number of functions that perform asynchronous operations and execute a callback function upon completion of whatever the async operation is. Once they're all complete it calls the last function it received as a 'completion handler'. Example that I wrote out without bothering to test at all (treat it as pseudo-code):
So that will start by beginning the jQuery fadeOut animation on the pageContainer html element, while immediately doing an ajax call to get another page's data. Once both operations are complete, it will take the new page data, put it into the pageContainer element, and fade it back in.