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
found the solution
code runs every 2 seconds and after 10 seconds it stops
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.
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.