Waiting for multiple Events

At first blush, something like this would definitely work:

var executed_this = false, executed_sth = false;

function execute_this() {
  executed_this = true;
  combined_execution();
}

function execute_sth() {
  executed_sth = true;
  combined_execution();
}

function combined_execution() {
  if (executed_this && executed_sth) {
    // magic!
  }
}

But is not extensible (what if you want a third event to wait on?). A counter would work:

var wait_on = 2;

function execute_this() {
  combined_execution();
}

function execute_sth() {
  combined_execution();
}

function combined_execution() {
  wait_on--;
  if (wait_on === 0) {
    // magic!
  }
}

Is more extensible, but that assumes that the events only fire once. Either way, these are the primatives that can control the type of flow control you are asking for, and everything else is (for the most part) a higher level abstraction on these two.


You can make Promises that resolve when the events fire, and wait for both of them to be ready.

var dcl = new Promise(function(resolve) {
    document.addEventListener("DOMContentLoaded",resolve,false);
})
var deviceready = new Promise(function(resolve) {
    document.addEventListener("deviceready", resolve, false);
})

Promise.all([dcl, deviceready]).then(function() {
    //both are ready
});