Skip to content

Instantly share code, notes, and snippets.

@duncanbeevers
Created March 14, 2011 06:38
Show Gist options
  • Save duncanbeevers/868846 to your computer and use it in GitHub Desktop.
Save duncanbeevers/868846 to your computer and use it in GitHub Desktop.
function AsynchDispatcher() {
var listeners = [],
m = 'message',
w = window;
function receiveMessage(index) {
index = parseInt(index.data || index);
setTimeout(listeners[index], 10);
if (index) {
w.postMessage(index - 1, location.origin);
} else {
w.removeEventListener(m, receiveMessage, false);
}
}
function add(listener) {
listeners.push(listener);
}
function fire() {
w.addEventListener(m, receiveMessage, false)
receiveMessage(listeners.length - 1);
}
this.add = add;
this.fire = fire;
}
@duncanbeevers
Copy link
Author

var d = new AsynchDispatcher();
var total = 25000;
var i = total;

var count = 0;
while (i--) {
  d.add((function(i) {
    return function() {
      if (0 == count) {
        console.log("Started at %o", new Date());
      }
      count++;
      if (count == total - 1) {
        console.log("Finished at %o", new Date());
      }
    }
  })(i));
}
d.fire();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment