Node.js
Give an operation a timeout signal
Use AbortSignal.timeout to create a signal that aborts after a deadline. Pass it to APIs that support cancellation rather than merely racing their promise against a timer.
Worked example
Node.js example · save as example.mjs and run node example.mjs
import {setTimeout as delay} from "node:timers/promises";
const signal = AbortSignal.timeout(5);
try {
await delay(100, "finished", {signal});
} catch (error) {
console.log(error.name, signal.aborted);
}How it works
The timers/promises operation listens to the signal and rejects when it aborts. With fetch, the signal can cancel the request or body read. Cancellation support belongs to the underlying operation; creating a signal alone does not stop unrelated work.
Limits and mistakes
An operation may need its own cleanup after cancellation, and remote servers may already have acted on a request. A client timeout is not proof that a write never happened. Distinguish timeout-related failures from other network errors.
Check the result
Expect AbortError true for this timer operation. Check the actual API’s rejection behavior rather than assuming every operation uses the same error name.
Sources
Reference documentation for the behavior used in this guide: