Skip to content

Instantly share code, notes, and snippets.

@josher19
Created February 6, 2012 09:31
Show Gist options
  • Save josher19/1751053 to your computer and use it in GitHub Desktop.
Save josher19/1751053 to your computer and use it in GitHub Desktop.
Async Limited Queue
var NQ = {
n: 1
,q: []
,add: function add(fn) { this.push(fn); this.next(); return this; }
,push: function push(fn) { this.q.push(fn); return this; }
,fire: function fire() { if (!this.q.length) return "empty"; this.run(this.q[0]);
this.q.shift(); return this.q.length; }
,cancel: function cancel() { this.q.length = 0; }
,success: function success() { console.log(arguments); }
,fail: function fail() { console.warn.apply(console, arguments); }
,cb: function cb() { NQ.success(arguments); NQ.fire(); }
,err: function err() { NQ.fail(arguments); NQ.fire(); }
,next: function next() { if (this.q.length < this.n) return this.fire(); else return "blocked"; }
,run: function run(fn) { return fn(NQ.err,NQ.cb); }
};
/* Based on suggestions from http://stereopsis.com/async/ */
/* Example usage: */
function goody(oops, ok) { setTimeout(function() {return ok(200 + "goody");}, 500); }
function baddy(oops, ok) { var start = new Date(); return setTimeout(function() { oops(NQ.q.length, "baddy", new Date().toString() ); }, 1000) }
NQ.push(goody); NQ.add(goody).next(); NQ.add(baddy).add(baddy).add(baddy).add(baddy).add(baddy).add(goody).add(baddy).push(goody).fire();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment