Last active
June 17, 2016 13:50
-
-
Save branneman/53b820be519b54bfc30a to your computer and use it in GitHub Desktop.
Function Invoker - Repeatedly invokes a function until it returns a truthy value
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
/** | |
* 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(); | |
}; | |
} |
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
// 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