Skip to content

Commit 9882f1c

Browse files
committed
Add abortAfterTimeout() utility to make it easy to add timeouts
1 parent 6ec4c09 commit 9882f1c

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

src/shared/protocol.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ export type RequestOptions = {
4848

4949
/**
5050
* Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request().
51+
*
52+
* Use abortAfterTimeout() to easily implement timeouts using this signal.
5153
*/
5254
signal?: AbortSignal;
5355
};

src/utils.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { abortAfterTimeout } from "./utils.js";
2+
3+
describe("abortAfterTimeout", () => {
4+
it("should abort after timeout", () => {
5+
const signal = abortAfterTimeout(0);
6+
expect(signal.aborted).toBe(false);
7+
8+
return new Promise((resolve) => {
9+
setTimeout(() => {
10+
expect(signal.aborted).toBe(true);
11+
resolve(true);
12+
}, 0);
13+
});
14+
});
15+
});

src/utils.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* Returns an AbortSignal that will enter aborted state after `timeoutMs` milliseconds.
3+
*/
4+
export function abortAfterTimeout(timeoutMs: number): AbortSignal {
5+
const controller = new AbortController();
6+
setTimeout(() => {
7+
controller.abort();
8+
}, timeoutMs);
9+
10+
return controller.signal;
11+
}

0 commit comments

Comments
 (0)