Skip to content

Instantly share code, notes, and snippets.

@johnhunter
Created April 5, 2014 12:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johnhunter/9991356 to your computer and use it in GitHub Desktop.
Save johnhunter/9991356 to your computer and use it in GitHub Desktop.
ease the pain of nested callbacks on animation
/*
createQueue - ease the pain of nested callbacks on animation
*/
function createQueue (stepCallback) {
var queue = [];
var isPaused;
var totalSteps = 0;
function next() {
var stepNumber = totalSteps - queue.length;
if (isPaused) { return; }
if (typeof stepCallback === 'function' && stepNumber > 0) {
stepCallback(stepNumber);
}
var step = queue.pop();
if (step) {
step(next);
}
}
return {
add: function(stepFn){
queue.unshift(stepFn);
totalSteps = queue.length;
return this;
},
run: function(){
isPaused = false;
next();
return this;
},
pause: function(){
isPaused = true;
return this;
}
};
}
//-- usage
var q = createQueue(afterEachStep);
q.add(fakeStep);
q.add(fakeStep);
q.add(fakeStep);
q.add(fakeStep);
q.run();
function afterEachStep (stepCount) {
console.log('callback after step ', stepCount);
}
function fakeStep (next){
// do something like animate({...}, 1000, next);
// following just simulates an animation
console.log('hello');
setTimeout(next, 500);
}
@tomrandle
Copy link

Thanks John! I'll try it out this evening. Hope you're having a good weekend!

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