skip to Main Content

How to make javascript exit the loop (time based) if the code stucks at an API call and it just hangs there forever?

pseudo code:

for loop

— api call

— if got response from "api call" in 5 seconds, break for loop

please be kind and answer the question. if it’s not relevant please just skip this question and don’t be a bully

2

Answers


  1. Chosen as BEST ANSWER

    found the solution

    code runs every 2 seconds and after 10 seconds it stops

      function example(){
        var thisinterval = setInterval(() => {
            console.log("testing")
            setTimeout(() => {
                clearInterval(thisinterval)
            }, 10*1000);
        }, 2*1000);
    }
    

  2. To do this, we can use Promise and setTimeout.

    First, we need to make the Promise by wrapping the API call with it. This will tell the code to wait for the response and continue when it’s ready, or stop if there’s a problem or it takes too long.

    for (let i = 0; i < iterations; i++) {
      const promise = makeAPICall();
      const timeout = setTimeout(() => {
        reject(new Error('Response took too long'));
      }, 5000);
        
      promise.then((response) => {
    
        clearTimeout(timeout);
    
        break;
      }).catch((error) => {
    
        clearTimeout(timeout);
    
      });
    }
    

    This way, if the API call takes longer than 5 seconds, the promise will be rejected, the timeout will be cleared, and the for loop will continue to the next iteration.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search