Posts Add a timeout to fetch
Post
Cancel

Add a timeout to fetch

This function returns 504 after time has passed. Instead of letting the user wait for the API to timeout which could take 60 seconds, it’s better to give the user feedback after a few seconds instead. This is of course dependent on which type of API you’re dealing with. If the API is fetching alot of data a timeout might be a bad idea, but if you’re communicating with an CMS it might be more useful.

The arguments this takes are:

url - The fetch url

time - The time in ms before the function return 504

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const fetchWithTimeout = (url, time) => {
  return new Promise((resolve, reject) => {
    const timeout = setTimeout(() => reject(504), time);
    return fetch(url).then(
      (response) => {
        clearTimeout(timeout);
        return resolve(response);
      },
      (rejectReason) => {
        clearTimeout(timeout);
        return reject(rejectReason);
      }
    );
  });
};

Usage:

1
2
3
4
5
6
// In an async function
try {
  const res = await fetchWithTimeout("/api-url", 2000);
} catch (err) {
  console.log(err) // Will return the 504 as entered in the reject
}
This post is licensed under CC BY 4.0 by the author.