Skip to content

Instantly share code, notes, and snippets.

@dtmrc
Forked from davej/fetch-timeout.js
Created February 5, 2022 20:13
Show Gist options
  • Save dtmrc/49f31271979e32a705ce76da4503b0a1 to your computer and use it in GitHub Desktop.
Save dtmrc/49f31271979e32a705ce76da4503b0a1 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)
)
]);
@dtmrc
Copy link
Author

dtmrc commented Feb 5, 2022


via @davej
Promise.race: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/race
fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch


via @maurits-tellow
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


@dtmrc
Copy link
Author

dtmrc commented Feb 5, 2022

Handling timeout in Axios

https://medium.com/@masnun/handling-timeout-in-axios-479269d83c68
Abu Ashraf Masnun Jun 17, 2019

If you’re making http requests using the axios library on a browser or in a node app, do make sure that you have a timeout set. The default timeout is set to 0 which indicates no timeout. With that default value, any remote end can keep us waiting for the requested resource for an indefinite period. With limited resources at hand, we really wouldn’t like that to happen. Let’s set a timeout instead.

the error code, error message and the stack trace. It looks something like this:

ECONNABORTED
timeout of 2ms exceeded
Error: timeout of 2ms exceeded
    at createError (/Users/masnun/Projects/medium/node_modules/axios/lib/core/createError.js:16:15)
    at Timeout.handleRequestTimeout (/Users/masnun/Projects/medium/node_modules/axios/lib/adapters/http.js:252:16)
    at listOnTimeout (timers.js:324:15)
    at processTimers (timers.js:268:5)

— Set the value to timeout in a config object
— Timeout values are in milliseconds, { timeout: 2 } means 2ms timeout, not 2s.

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