That's cool, but you're kind of mixing together a few different pieces of functionality. To me, this kind of thing would be much more readable using promises to wrap the asynchronous nature of the code. Assuming you used when.js, you could do something like:<p><pre><code> function delay(fn, ms) {
return when(function (resolve) {
setTimeout(function () {
fn();
resolve();
}, ms || 0);
});
}
function eachDelay(arr, fn, ms) {
arr.reduce(function (prev, curr) {
prev.then(function () {
return fn(curr);
});
}, when(null));
}
</code></pre>
That looks more complicated on the surface, but in reality, libraries like when.js and underscore give you convenience functions that abstract away much of this boilerplate. I didn't want to presume anything but the bare `when`. If you really get used to programming "the combinator way", you get to the point where you write these cute little primative combinators that can be combined in very readable ways. If you like coding in this style, definitely check out Javascript Allongé (<a href="https://leanpub.com/javascript-allonge/read" rel="nofollow">https://leanpub.com/javascript-allonge/read</a>), which makes this all look far more appealing than I've done here.