Line data Source code
1 : export interface TimedSignal {
2 : readonly signal: AbortSignal | undefined
3 : /** Disarms the timer; call once the response body has been read. */
4 : readonly release: () => void
5 : }
6 :
7 : /** Joins the caller's signal with an abort after `timeoutMs`, if one is set. */
8 0 : export function timedSignal(
9 : signal: AbortSignal | undefined,
10 : timeoutMs: number | undefined
11 : ): TimedSignal {
12 0 : if (timeoutMs === undefined) return { signal, release: () => undefined }
13 0 : const controller = new AbortController()
14 0 : const timer = setTimeout(() => controller.abort(), timeoutMs)
15 0 : const onAbort = () => controller.abort(signal?.reason)
16 0 : if (signal?.aborted) onAbort()
17 0 : else signal?.addEventListener('abort', onAbort, { once: true })
18 0 : return {
19 : signal: controller.signal,
20 : release: () => {
21 0 : clearTimeout(timer)
22 0 : signal?.removeEventListener('abort', onAbort)
23 : }
24 : }
25 : }
|