The approach itself (i.e. using a counter) is reasonable, but the hard-coded 2
and DoStuff
limits its use.
You could do something like this, to derive more generic implementation:
function createCounter(count, callback) {
count || (count = 1); // default to 1
(typeof callback === 'function') || (callback = function () {}); // default to no-op
return function () {
--count || callback();
};
}
Now you have a function that returns a specialized "done" function. Use like so:
var done = createCounter(2, DoStuff);
elem1.executeAsync(function () {
done();
});
elem2.executeAsync(function () {
done();
});
Incidentally, this can be shortened to:
var done = createCounter(2, DoStuff);
elem1.executeAsync(done);
elem2.executeAsync(done);
(of course, your actual code is likely more complex)
However, I'd say you should also look into the Promise/Deferred patterns.
For instance, using jQuery's implementation (and assuming executeAsync
returns a promise) you can do this
$.when(elem1.executeAsync(), elem2.executeAsync()).then(DoStuff);
DoStuff()
called only when both are done? – SomeKittens Nov 12 '12 at 15:43