Last active
September 8, 2021 17:46
-
-
Save ken107/dcaad2168fe7f58f6868263a936a663f to your computer and use it in GitHub Desktop.
Repeat an action `max` number of times or `until` some condition, with optional `delay` between repetitions
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
/** | |
* Repeat an action | |
* @param {Object} opt - options | |
* @param {Function} opt.action - action to repeat | |
* @param {Function} opt.until - termination condition | |
* @param {Number} opt.delay - delay between actions | |
* @param {Number} opt.max - maximum number of repetitions | |
* @returns {Promise} | |
*/ | |
function repeat(opt) { | |
if (!opt || !opt.action) throw new Error("Missing action") | |
return iter(1) | |
function iter(n) { | |
return Promise.resolve() | |
.then(opt.action) | |
.then(function(result) { | |
if (opt.until && opt.until(result)) return result | |
if (opt.max && n >= opt.max) return result | |
if (!opt.delay) return iter(n+1) | |
return new Promise(function(f) {setTimeout(f, opt.delay)}).then(iter.bind(null, n+1)) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment