Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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);
}

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