AbortSignal Timeout Ends Slow Work

AbortSignal.timeout builds a deadline signal that aborts itself with a TimeoutError; wire it into slow work with throwIfAborted and one abort listener.

JavascriptResilience

Code

javascriptsnippet
26 lines
// AbortSignal.timeout:到达时限自动 abort,reason 是 TimeoutError DOMException
const signal = AbortSignal.timeout(80);
signal.addEventListener('abort', () => {
  console.log('aborted reason:', signal.reason.name);
});

// 慢操作只挂一个 abort 监听:收到信号清理定时器并拒绝
async function slowWork(sig) {
  return await new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve('done'), 5000);
    sig.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(sig.reason);
    }, { once: true });
  });
}

try {
  await slowWork(signal);
} catch (err) {
  console.log('work ended with:', err.name);
}

// 信号还活着时 throwIfAborted 正常返回;已中止则直接抛 reason
AbortSignal.timeout(5000).throwIfAborted();
console.log('throwIfAborted returned: still live');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

aborted reason: TimeoutError
work ended with: TimeoutError
throwIfAborted returned: still live

How the snippet works

AbortSignal Timeout Ends Slow Work is built around the function slowWork.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Applying it

Entry signature: async function slowWork(sig)

Running the file prints labeled results such as aborted reason:, work ended with:, throwIfAborted returned: still live — each operation’s effect is visible in the output.

Statements that matter

return await new Promise((resolve, reject) => {
  const timer = setTimeout(() => resolve('done'), 5000);
  sig.addEventListener('abort', () => {
    clearTimeout(timer);
    reject(sig.reason);
  }, { once: true });
});
signal.addEventListener('abort', () => {
  console.log('aborted reason:', signal.reason.name);
});
await slowWork(signal);

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `slowWork` at load time.