Skip to content

Commit a8362d8

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

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-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+
* `duration` {number} The numer 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: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,17 @@ const {
2929
}
3030
} = require('internal/errors');
3131

32+
const {
33+
validateUint32,
34+
} = require('internal/validators');
35+
36+
const {
37+
DOMException,
38+
} = internalBinding('messaging');
39+
3240
const kAborted = Symbol('kAborted');
3341
const kReason = Symbol('kReason');
42+
const kTimeout = Symbol('kTimeout');
3443

3544
function customInspect(self, obj, depth, options) {
3645
if (depth < 0)
@@ -82,6 +91,23 @@ class AbortSignal extends EventTarget {
8291
static abort(reason) {
8392
return createAbortSignal(true, reason);
8493
}
94+
95+
/**
96+
* @param {number} delay
97+
* @returns {AbortSignal}
98+
*/
99+
static timeout(delay) {
100+
validateUint32(delay, 'delay', true);
101+
const signal = createAbortSignal();
102+
signal[kTimeout] = setTimeout(() => {
103+
abortSignal(
104+
signal,
105+
new DOMException(
106+
'The operation was aborted due to timeout',
107+
'TimeoutError'));
108+
}, delay);
109+
return signal;
110+
}
85111
}
86112

87113
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)