Abort Signal Timeout Wrapper
A typed helper that links an AbortSignal to a deadline so in-flight requests are cancelled deterministically and listeners never leak.
Code
export interface DeadlineHandle {
readonly signal: AbortSignal;
cleanup(): void;
}
export function withDeadline(timeoutMs: number, parent?: AbortSignal): DeadlineHandle {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
throw new RangeError("timeoutMs must be a positive number");
}
const controller = new AbortController();
if (parent?.aborted) {
controller.abort(parent.reason);
} else if (parent) {
parent.addEventListener("abort", () => controller.abort(parent.reason), { once: true });
}
const timer: ReturnType<typeof setTimeout> = setTimeout(() => {
controller.abort(new Error(`deadline exceeded after ${timeoutMs}ms`));
}, timeoutMs);
// unref is a Node extension absent in browser typings
const maybeUnref = timer as unknown as { unref?: () => void };
if (typeof maybeUnref.unref === "function") maybeUnref.unref();
return {
signal: controller.signal,
cleanup() {
clearTimeout(timer);
controller.abort(new Error("deadline cancelled"));
},
};
}A request without a deadline hangs until the socket times out, and manually wiring AbortSignal.timeout leaks listeners on long-lived signals.
Use case: engineers bounding request latency with cancellable operations
Inputs / outputs
- Input: a timeout in milliseconds, an optional parent signal to link
- Output: an AbortSignal that aborts at the deadline or when the parent aborts, plus a cleanup function
Error conditions
- non-positive timeout
- parent already aborted at creation time
Approach
compose an internal controller; timer aborts it at the deadline; parent abort propagates; cleanup clears the timer and removes the parent listener so nothing leaks.
Implementation
export interface DeadlineHandle {
readonly signal: AbortSignal;
cleanup(): void;
}
export function withDeadline(timeoutMs: number, parent?: AbortSignal): DeadlineHandle {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
throw new RangeError("timeoutMs must be a positive number");
}
const controller = new AbortController();
if (parent?.aborted) {
controller.abort(parent.reason);
} else if (parent) {
parent.addEventListener("abort", () => controller.abort(parent.reason), { once: true });
}
const timer: ReturnType<typeof setTimeout> = setTimeout(() => {
controller.abort(new Error(`deadline exceeded after ${timeoutMs}ms`));
}, timeoutMs);
// unref is a Node extension absent in browser typings
const maybeUnref = timer as unknown as { unref?: () => void };
if (typeof maybeUnref.unref === "function") maybeUnref.unref();
return {
signal: controller.signal,
cleanup() {
clearTimeout(timer);
controller.abort(new Error("deadline cancelled"));
},
};
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { withDeadline } from "./example.ts";
test("aborts after the deadline", async () => {
const handle = withDeadline(10);
assert.equal(handle.signal.aborted, false);
await new Promise((r) => setTimeout(r, 30));
assert.equal(handle.signal.aborted, true);
});
test("propagates parent abort immediately", () => {
const parent = new AbortController();
const handle = withDeadline(10_000, parent.signal);
assert.equal(handle.signal.aborted, false);
parent.abort(new Error("caller cancelled"));
assert.equal(handle.signal.aborted, true);
assert.equal(String(handle.signal.reason), "Error: caller cancelled");
handle.cleanup();
});
test("already aborted parent aborts at creation", () => {
const parent = new AbortController();
parent.abort(new Error("already gone"));
const handle = withDeadline(10_000, parent.signal);
assert.equal(handle.signal.aborted, true);
});
test("rejects non-positive timeouts", () => {
assert.throws(() => withDeadline(0), RangeError);
assert.throws(() => withDeadline(-1), RangeError);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node –experimental-strip-types example.ts
Limitations and error handling
no reason propagation details beyond the deadline message; no fetch integration built in.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Report a problem with this exampleOpens a pre-filled issue on GitHub.