Last active
September 8, 2021 22:44
-
-
Save n18l/25a8e2534acc807bf5260d6e7feb9a70 to your computer and use it in GitHub Desktop.
Repeatedly attempts to execute a function based on provided criteria that are reevaluated on each attempt. A dumb function for dumb situations that shouldn't exist.
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
/** | |
* Repeatedly attempts to execute a function based on provided criteria that are | |
* reevaluated on each attempt. | |
* | |
* @param {Function} criteria The criteria to evaluate on each attempt to determine if the | |
* success handler should be invoked. Note that the result of this | |
* function will be coerced to a boolean value. | |
* @param {Function} onSuccess A function to invoke if an attempt evaluates the criteria as true. | |
* @param {Function} onFailure A function to invoke if all attempts evaluate the criteria as false. | |
* @param {Number} intervalMs How frequently (in milliseconds) to reevaluate the criteria. | |
* @param {Number} maxAttempts How many times the criteria should be reevaluated. | |
*/ | |
function attempt(criteria, onSuccess, onFailure, intervalMs, maxAttempts) { | |
let attemptsRemaining = maxAttempts; | |
console.log(`Making ${maxAttempts} attempts at ${intervalMs}ms intervals`); | |
const interval = setInterval(() => { | |
attemptsRemaining -= 1; | |
console.log( | |
`Making attempt ${ | |
maxAttempts - attemptsRemaining | |
} of ${maxAttempts}` | |
); | |
if (!criteria) { | |
console.log(`Attempt failed!`); | |
if (attemptsRemaining === 0) { | |
clearInterval(interval); | |
onFailure(); | |
} | |
return; | |
} | |
console.log(`Attempt succeeded!`); | |
clearInterval(interval); | |
onSuccess(); | |
}, intervalMs); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment