fetch w/ request timeout by AbortController
// @description fetch w/ request timeout by AbortController
// @license CC0 Univ PD https://creativecommons.org/publicdomain/zero/1.0/
// @author noromanba https://noromanba.github.com
// @version 2018.5.11.0
(async () => {
'use strict';
const controller = new AbortController();
const signal = controller.signal;
signal.onabort = () => {
console.error('aborted?', signal.aborted);
};
const TIMEOUT_MSEC = 1;
const timer = setTimeout(() => controller.abort(), TIMEOUT_MSEC);
try {
const response = await fetch(location.href, { signal, });
const text = await response.text();
console.log(text);
} catch (e) {
console.error(e);
} finally {
clearTimeout(timer);
}
// Promise {<pending>}
// aborted? true
// DOMException: The user aborted a request.
})();
Chrome/ium v66+ implemented AbortController
- https://developer.mozilla.org/en-US/docs/Web/API/AbortController
- https://developer.mozilla.org/en-US/docs/Web/API/AbortController/AbortController
- https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
Browser | Version | Detail |
---|---|---|
Chromium | 66.0.3359.139 | 66.0.3359.139-0ubuntu0.16.04.3 |
Firefox | 60.0 20180509235617 | 60.0+build2-0ubuntu0.16.04.1 |