Skip to content

Instantly share code, notes, and snippets.

@Qard
Created April 9, 2011 23:47
Show Gist options
  • Save Qard/911901 to your computer and use it in GitHub Desktop.
Save Qard/911901 to your computer and use it in GitHub Desktop.
Build callback chains without ridiculous indentation!
function chainer(){
var chain = [];
function add(callback) { chain.push(callback); }
function next() { if (chain.length) { chain[0](); chain.shift(); } }
return { add: add, push: add, run: next, start: next, next: next };
}
// Make a new chain.
var chain = new chainer();
// Add a function
chain.add(function(){
console.log('First!');
chain.next();
});
// Add a function
chain.add(function(){
console.log('Second!');
});
chain.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment