Timeout Limit to Asynchronous JavaScript Functions
The case
I have a page that gets data from an API (Swapi). I want to make an asynchronous call to fetch the data but I don't want the users to wait too long.
Ideally, the maximum waiting time would be 500ms and if nothing happens, I will show the "fallback" data. How can we tackle this?
The Solution
Let's start with the basic function that supposedly takes a while to be fetched (1sec). We will be using Deelay.me to slow loading the API.
We agreed that 1 second is too long. The acceptable waiting time is 500 ms. So let's create a timeLimit function to set the max waiting time.
We need to make sure to provide the fallback response or data, should the async `getPlanets` function takes over 500ms to complete the task. Let's use the `timeLimit` function above on the `onApiTimeout` function and provide the fallback.
Now we need to make sure that the `getPlanets` adhere the time limit rule. If `getPlanets` takes longer than 500ms, we will give the fallback response instead of the one from the API. The key here is to use `Promise.race`.
The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise. Learn more here.
Finally, let's create a async function called `initGetPlanets` where we can try to get `planets` from `getPlanetsWithTimeLimit` and catch if there's an error to the request.
To test if the concept works, we can adjust the `deelay` on `getPlanets` function and/or the `timeLimit` inside the `onApiTimeout` function.
If you check out the console, you will see that the `planets` is coming from the Swapi API.
If you adjust the `deelay` to larger than 500ms, you will get the fallback inside planets variable.
To see this concept in action, you can go to this Codepen.
Any questions or suggestions for better implementations? Write to me 😀