Skip to content

Instantly share code, notes, and snippets.

@davej
Last active July 1, 2022 23:35
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save davej/728b20518632d97eef1e5a13bf0d05c7 to your computer and use it in GitHub Desktop.
Save davej/728b20518632d97eef1e5a13bf0d05c7 to your computer and use it in GitHub Desktop.
Add a pseudo timeout/deadline to a request using the ES6 fetch api
Promise.race([
fetch('/foo'),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), 7000)
)
]);
@geckofu
Copy link

geckofu commented Aug 25, 2017

👏

@Palisand
Copy link

🙌

@michielmetcake
Copy link

👍

@maurits-tellow
Copy link

maurits-tellow commented Mar 30, 2020

This does not cancel the (hanging) request. Use this solution instead: https://stackoverflow.com/a/57888548/13037768.

const fetchTimeout = (url, ms, { signal, ...options } = {}) => {
    const controller = new AbortController();
    const promise = fetch(url, { signal: controller.signal, ...options });
    if (signal) signal.addEventListener("abort", () => controller.abort());
    const timeout = setTimeout(() => controller.abort(), ms);
    return promise.finally(() => clearTimeout(timeout));
};

Not supported in Internet Explorer (it is in Edge). See https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility

@jimmywarting
Copy link

Not supported in Internet Explorer (it is in Edge).

ppl should stop supporting IE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment