Search code examples
javascripthtmlfunctionapirest

how to write a if statement for fetch('link'). So that when one fetch('link1') takes more than 3 second to respond then use the other fetch('link2')


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..


Solution

  • 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