Skip to content

Instantly share code, notes, and snippets.

@csandman
Created June 17, 2020 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csandman/ec5c89401f2da29869bf03887cb21a6d to your computer and use it in GitHub Desktop.
Save csandman/ec5c89401f2da29869bf03887cb21a6d to your computer and use it in GitHub Desktop.
An implementation of the fetch api with a timeout option
function fetchWithTimeout(url, options, timeout, onTimeout) {
const timer = new Promise((resolve) => {
setTimeout(resolve, timeout, {
timeout: true,
});
});
return Promise.race([fetch(url, options), timer])
.then((response) => {
if (response.timeout) {
onTimeout();
}
return response;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment