0

How to write an if statement for fetch('link'). So that when one fetch('link1') takes more than 3 seconds to respond then, timeout the link1 use the other fetch('link2')

if ()
      {
        fetch('https://api.apilayer.com/exchangerates_data/latest?base=USD', requestOptions)

        .then(response => response.json())
        .catch(error => {
            console.log('Error', error);
        });
      
      return false;
      } else 
      {
        fetch("https://api.apilayer.com/fixer/latest?base=USD", requestOptions)

        .then(response => response.json())
        .catch(error => {
            console.log('Error', error);
        });
      
      return false;
      }

I have tried the above code but doesn't work..

  • `setTimeout('#result',3000)` is not how [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) works - – Jaromanda X Feb 01 '23 at 08:39

1 Answers1

0

You could use something similar to the answer submitted to this question on how to measure the time taken to execute a function and use it for comparison within the conditional, e.g. (timeTaken > 3000)

How to measure time taken by a function to execute

Hope this helps to steer you in the right direction

Chadrak
  • 13
  • 2