Skip to content

Instantly share code, notes, and snippets.

@estelsmith
Created December 7, 2023 22:05
Show Gist options
  • Save estelsmith/4ffd399e44f25d5618cd92b3c78b21b3 to your computer and use it in GitHub Desktop.
Save estelsmith/4ffd399e44f25d5618cd92b3c78b21b3 to your computer and use it in GitHub Desktop.
JavaScript Fetch w/ Timeout
/**
* A wrapper around the fetch api that will abort after a configurable amount of time has passed.
*
* @param {URL|string} input
* @param {RequestInit?} init
* @param {number?} providedTimeout
* @returns {Promise<Response>}
*/
export default async function fetchTimeout(input, init, providedTimeout) {
const timeout = providedTimeout ?? config.timeouts.defaultTimeout;
const abortController = new AbortController();
const timer = setTimeout(() => abortController.abort(), timeout);
const response = await fetch(
input,
{
signal: abortController.signal,
...(init || {})
}
);
clearTimeout(timer);
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment