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①

瀏覽器相容性