Skip to content

Commit 073a6fa

Browse files
committed
Support automatic disposal
1 parent cd3c44a commit 073a6fa

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

index.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,11 @@ export default function timeoutSignal(timeout) {
1212
// Allow Node.js processes to exit early if only the timeout is running
1313
timeoutId?.unref?.();
1414

15-
return controller.signal;
15+
const {signal} = controller;
16+
17+
signal[Symbol.dispose] = () => {
18+
clearTimeout(timeoutId);
19+
}
20+
21+
return signal;
1622
}

readme.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,25 @@ try {
2525
}
2626
```
2727

28+
With [`using`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using#browser_compatibility) syntax for automatic disposal:
29+
30+
```js
31+
import timeoutSignal from 'timeout-signal';
32+
33+
async function hello() {
34+
using signal = timeoutSignal(5000);
35+
36+
try {
37+
const response = await fetch('https://www.google.com', {signal});
38+
// Handle response
39+
} catch (error) {
40+
if (signal.aborted) {
41+
// Handle abortion
42+
}
43+
}
44+
}
45+
```
46+
2847
## API
2948

3049
### timeoutSignal(timeout)

test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import test from 'ava';
2+
import {setTimeout as delay} from 'node:timers/promises';
23
import {pEvent} from 'p-event';
34
import timeSpan from 'time-span';
45
import timeoutSignal from './index.js';
@@ -16,3 +17,18 @@ test('main', async t => {
1617
t.true(signal.aborted);
1718
t.true(end() < 500);
1819
});
20+
21+
test('using', async t => {
22+
let isAborted = false;
23+
24+
{
25+
using signal = timeoutSignal(300);
26+
signal.addEventListener('abort', () => {
27+
isAborted = true;
28+
})
29+
await delay(100);
30+
}
31+
32+
await delay(500);
33+
t.false(isAborted);
34+
})

0 commit comments

Comments
 (0)