Iterating over a Javascript array at a consistent rate
blog.jackmontgomery.io
blog.jackmontgomery.io
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));
}
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é (https://leanpub.com/javascript-allonge/read), which makes this all look far more appealing than I've done here.If you want to really understand promises, this is a good resource: https://gist.github.com/domenic/3889970