Created
April 5, 2014 12:28
-
-
Save johnhunter/9991356 to your computer and use it in GitHub Desktop.
ease the pain of nested callbacks on animation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks John! I'll try it out this evening. Hope you're having a good weekend!