Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

Palisand commented Aug 31, 2017

🙌

@michielmetcake
Copy link

michielmetcake commented May 29, 2018

👍

@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

jimmywarting commented Aug 7, 2020

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