Skip to content

Instantly share code, notes, and snippets.

@ken107
Last active September 8, 2021 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ken107/dcaad2168fe7f58f6868263a936a663f to your computer and use it in GitHub Desktop.
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
/**
* 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