Skip to content

Instantly share code, notes, and snippets.

@n18l
Last active September 8, 2021 22:44
Show Gist options
  • Save n18l/25a8e2534acc807bf5260d6e7feb9a70 to your computer and use it in GitHub Desktop.
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.
/**
* 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