Skip to content

Commit f04a7fb

Browse files
committed
lib: add AbortSignal.timeout
Refs: whatwg/dom#1032 Signed-off-by: James M Snell <[email protected]>
1 parent 0defcbb commit f04a7fb

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

doc/api/globals.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,17 @@ changes:
104104

105105
Returns a new already aborted `AbortSignal`.
106106

107+
#### Static method: `AbortSignal.timeout(delay)`
108+
109+
<!-- YAML
110+
added: REPLACEME
111+
-->
112+
113+
* `delay` {number} The number of milliseconds to wait before triggering
114+
the AbortSignal.
115+
116+
Returns a new `AbortSignal` which will be aborted in `delay` milliseconds.
117+
107118
#### Event: `'abort'`
108119

109120
<!-- YAML

lib/internal/abort_controller.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,19 @@ const {
2929
}
3030
} = require('internal/errors');
3131

32+
const {
33+
validateUint32,
34+
} = require('internal/validators');
35+
36+
const {
37+
DOMException,
38+
} = internalBinding('messaging');
39+
40+
const { setTimeout } = require('timers');
41+
3242
const kAborted = Symbol('kAborted');
3343
const kReason = Symbol('kReason');
44+
const kTimeout = Symbol('kTimeout');
3445

3546
function customInspect(self, obj, depth, options) {
3647
if (depth < 0)
@@ -82,6 +93,23 @@ class AbortSignal extends EventTarget {
8293
static abort(reason) {
8394
return createAbortSignal(true, reason);
8495
}
96+
97+
/**
98+
* @param {number} delay
99+
* @returns {AbortSignal}
100+
*/
101+
static timeout(delay) {
102+
validateUint32(delay, 'delay', true);
103+
const signal = createAbortSignal();
104+
signal[kTimeout] = setTimeout(() => {
105+
abortSignal(
106+
signal,
107+
new DOMException(
108+
'The operation was aborted due to timeout',
109+
'TimeoutError'));
110+
}, delay);
111+
return signal;
112+
}
85113
}
86114

87115
ObjectDefineProperties(AbortSignal.prototype, {

test/parallel/test-abortcontroller.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,13 @@ const { ok, strictEqual, throws } = require('assert');
153153
const signal = AbortSignal.abort('reason');
154154
strictEqual(signal.reason, 'reason');
155155
}
156+
157+
{
158+
// Test AbortSignal timeout
159+
const signal = AbortSignal.timeout(10);
160+
ok(!signal.aborted);
161+
setTimeout(() => {
162+
ok(signal.aborted);
163+
strictEqual(signal.reason.code, 23);
164+
}, 20);
165+
}

0 commit comments

Comments
 (0)