I'm looking for a better way to retry if a function returns true or false
function foo() { //
var tabList = window.content.document.getElementById('compTabs') // this might be null if page is not loaded and further code wont work
if (!tabList) { // stop here if tab list is null
return false;
}
// continue and finish function
}
// this is a loop that will go trough an array and this check needs to happen for each element of the array
for (var i; i < loopLenght; i++) {
// This is the actual code nothing else happens here.
if ( !foo() ) {
// try again
if ( !foo() ) {
// try one more time
if ( !foo() ) {
console.log('Failed')
}
}
}
// a lot more code coming here that should only run one per iteration
}
I'm just looking for a nicer, cleaner way to write the code above.
var retries = 5;
var success = false;
while (retries-- > 0 && !(success = foo())) {}
console.log(success);
Here, retries-- counts down with every loop iteration and success = foo() executes foo() and saves the result into success.
If either retries hits 0 or success becomes true, the loop stops. A loop body is not needed.
Warning: This will not work if foo() is an asynchronous function.
Are you in a browser? (As opposed to Node etc.) Does it have to retry specifically N times?
while (!condition) { }
But that'll block and hang your thread.
If you want to poll ...
function whileConditionNotMet()
{
if (!condition) {
setTimeout(whileConditionNotSet, 1000);
return false;
}
// Condition met
// ...
return true;
}
You could limit the number of times it checks by incrementing a static variable:
function whileConditionNotMet()
{
if ( typeof whileConditionNotMet.counter == 'undefined' ) {
whileConditionNotMet.counter = 0;
}
if (whileConditionNotMet.counter++ > 10) {
// Timeout
// ...
return false;
}
if (!condition) {
setTimeout(whileConditionNotSet, 1000);
return false;
}
// Condition met
// ...
return true;
}
...or...
var counter = 0;
while (!condition && counter++ < 10) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With