combinedAbortSignal.ts
utils/combinedAbortSignal.ts
No strong subsystem tag
48
Lines
1714
Bytes
1
Exports
1
Imports
10
Keywords
What this is
This page documents one file from the repository and includes its full source so you can read it without leaving the docs site.
Beginner explanation
This file is one piece of the larger system. Its name, directory, imports, and exports show where it fits. Start by reading the exports and related files first.
How it is used
Start from the exports list and related files. Those are the easiest clues for where this file fits into the system.
Expert explanation
Architecturally, this file intersects with general runtime concerns. It contains 48 lines, 1 detected imports, and 1 detected exports.
Important relationships
Detected exports
createCombinedAbortSignal
Keywords
signaltimercombinedabortsignalcleanupabortabortcombinedtimeouttimeoutmssignalb
Detected imports
./abortController.js
Source notes
This page embeds the full file contents. Small or leaf files are still indexed honestly instead of being over-explained.
Full source
import { createAbortController } from './abortController.js'
/**
* Creates a combined AbortSignal that aborts when the input signal aborts,
* an optional second signal aborts, or an optional timeout elapses.
* Returns both the signal and a cleanup function that removes event listeners
* and clears the internal timeout timer.
*
* Use `timeoutMs` instead of passing `AbortSignal.timeout(ms)` as a signal —
* under Bun, `AbortSignal.timeout` timers are finalized lazily and accumulate
* in native memory until they fire (measured ~2.4KB/call held for the full
* timeout duration). This implementation uses `setTimeout` + `clearTimeout`
* so the timer is freed immediately on cleanup.
*/
export function createCombinedAbortSignal(
signal: AbortSignal | undefined,
opts?: { signalB?: AbortSignal; timeoutMs?: number },
): { signal: AbortSignal; cleanup: () => void } {
const { signalB, timeoutMs } = opts ?? {}
const combined = createAbortController()
if (signal?.aborted || signalB?.aborted) {
combined.abort()
return { signal: combined.signal, cleanup: () => {} }
}
let timer: ReturnType<typeof setTimeout> | undefined
const abortCombined = () => {
if (timer !== undefined) clearTimeout(timer)
combined.abort()
}
if (timeoutMs !== undefined) {
timer = setTimeout(abortCombined, timeoutMs)
timer.unref?.()
}
signal?.addEventListener('abort', abortCombined)
signalB?.addEventListener('abort', abortCombined)
const cleanup = () => {
if (timer !== undefined) clearTimeout(timer)
signal?.removeEventListener('abort', abortCombined)
signalB?.removeEventListener('abort', abortCombined)
}
return { signal: combined.signal, cleanup }
}