Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active June 17, 2016 13:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/53b820be519b54bfc30a to your computer and use it in GitHub Desktop.
Save branneman/53b820be519b54bfc30a to your computer and use it in GitHub Desktop.
Function Invoker - Repeatedly invokes a function until it returns a truthy value
/**
* Invoker
* Repeatedly invokes a function until it returns a truthy value
*
* @see https://gist.github.com/branneman/53b820be519b54bfc30a
* @param {Number} limit - The amount of total calls before we timeout
* @param {Number} interval - The amount of milliseconds between calls
* @param {Function} fn - The function to execute, must return a truthy value to indicate it's finished
* @param {Function} cb - The callback for when we're finished. Recieves 2 arguments: `error` and `result`
*/
function invoker(limit, interval) {
return function(fn, cb) {
var current = 0;
var _fn = function() {
current++;
var result = fn();
if (result) {
cb(null, result);
} else if (current < limit) {
setTimeout(_fn, interval);
} else {
cb(new Error('Limit exceeded!'), null);
cb = function() {};
}
};
_fn();
};
}
// Succeeds after 15 calls
var i = 0;
invoker(20, 100)(function() {
console.log(i);
return ++i > 15;
}, console.log);
// Fails after 20 calls
var ii = 0;
invoker(20, 100)(function() {
console.log(ii);
return ++ii > 22;
}, console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment