Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Retry function several times to see if it returns true

Tags:

javascript

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.

like image 667
Trax Avatar asked Feb 03 '26 16:02

Trax


2 Answers

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.

like image 156
Tomalak Avatar answered Feb 06 '26 07:02

Tomalak


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) { }
like image 25
wally Avatar answered Feb 06 '26 06:02

wally



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!