Skip to content

Instantly share code, notes, and snippets.

@noromanba
Created May 11, 2018 05:24
Show Gist options
  • Save noromanba/7e76cd75d15e27b102007298a8156d8f to your computer and use it in GitHub Desktop.
Save noromanba/7e76cd75d15e27b102007298a8156d8f to your computer and use it in GitHub Desktop.
fetch w/ request timeout by AbortController

fetch w/ timeout sample

fetch w/ request timeout by AbortController

code

// @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.
})();

Bookmarklet


APPENDIX

doc

Chrome/ium v66+ implemented AbortController

Environment

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment