Calling a function when all asynchronous calls complete Below is a simplified version of some code I am using to execute a function after all asynchronous calls complete.  Is this a reasonable piece of code? It seems to work.  Nothing would break if DoStuff() was called twice, though that would be very inefficient.

var i = 0;
var done = function () {
    i++;
    if (i &lt; 2) return;
    //Everything is done
    DoStuff();
};
elem1.executeAsync(function () {
    done();
});
elem2.executeAsync(function () {
    done();
});
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);