AbortSignal:timeout() 静态方法

Baseline 2024
新推出

自 ⁨2024 年 4 月⁩ 起,此功能可在最新的设备和浏览器版本中运行。此功能可能不适用于较旧的设备或浏览器。

注意:此功能在 Web Workers 中可用。

AbortSignal.timeout() 静态方法返回一个 AbortSignal,该信号将在指定时间后自动中止。

信号在超时时会以 TimeoutError DOMException 中止。

超时是基于活动时间而非经过时间的。如果代码正在暂停的 worker 中运行,或者文档位于后退/前进缓存("bfcache")中,则超时将 effectively 暂停。

要组合多个信号,您可以使用 AbortSignal.any(),例如,直接通过超时信号或调用 AbortController.abort() 来中止下载。

语法

js
AbortSignal.timeout(time)

参数

时间

返回的 AbortSignal 将在活动(毫秒)时间达到此值后中止。该值必须在 0 和 Number.MAX_SAFE_INTEGER 的范围内。

返回值

一个 AbortSignal

超时时,信号将以其 AbortSignal.reason 属性设置为 TimeoutError DOMException 中止;如果操作是用户触发的,则会以 AbortError DOMException 中止。

示例

下面是一个示例,展示了一个 fetch 操作,如果 5 秒后仍未成功,它将超时。请注意,如果方法不支持、浏览器按下了“停止”按钮或其他原因,这也可能会失败。

js
const url = "https://path_to_large_file.mp4";

try {
  const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
  const result = await res.blob();
  // …
} catch (err) {
  if (err.name === "TimeoutError") {
    // This exception is from the abort signal
    console.error("Timeout: It took more than 5 seconds to get the result!");
  } else if (err.name === "AbortError") {
    // This exception is from the fetch itself
    console.error(
      "Fetch aborted by user action (browser stop button, closing tab, etc.",
    );
  } else if (err.name === "TypeError") {
    console.error("AbortSignal.timeout() method is not supported");
  } else {
    // A network error, or some other problem.
    console.error(`Error: type: ${err.name}, message: ${err.message}`);
  }
}

规范

规范
DOM
# ref-for-dom-abortsignal-timeout①

浏览器兼容性