Skip to content

Commit

Permalink
lib: add AbortSignal.timeout
Browse files Browse the repository at this point in the history
Refs: whatwg/dom#1032
Signed-off-by: James M Snell <[email protected]>
  • Loading branch information
jasnell committed Nov 21, 2021
1 parent 0defcbb commit f04a7fb
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
11 changes: 11 additions & 0 deletions doc/api/globals.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,17 @@ changes:

Returns a new already aborted `AbortSignal`.

#### Static method: `AbortSignal.timeout(delay)`

<!-- YAML
added: REPLACEME
-->

* `delay` {number} The number of milliseconds to wait before triggering
the AbortSignal.

Returns a new `AbortSignal` which will be aborted in `delay` milliseconds.

#### Event: `'abort'`

<!-- YAML
Expand Down
28 changes: 28 additions & 0 deletions lib/internal/abort_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,19 @@ const {
}
} = require('internal/errors');

const {
validateUint32,
} = require('internal/validators');

const {
DOMException,
} = internalBinding('messaging');

const { setTimeout } = require('timers');

const kAborted = Symbol('kAborted');
const kReason = Symbol('kReason');
const kTimeout = Symbol('kTimeout');

function customInspect(self, obj, depth, options) {
if (depth < 0)
Expand Down Expand Up @@ -82,6 +93,23 @@ class AbortSignal extends EventTarget {
static abort(reason) {
return createAbortSignal(true, reason);
}

/**
* @param {number} delay
* @returns {AbortSignal}
*/
static timeout(delay) {
validateUint32(delay, 'delay', true);
const signal = createAbortSignal();
signal[kTimeout] = setTimeout(() => {
abortSignal(
signal,
new DOMException(
'The operation was aborted due to timeout',
'TimeoutError'));
}, delay);
return signal;
}
}

ObjectDefineProperties(AbortSignal.prototype, {
Expand Down
10 changes: 10 additions & 0 deletions test/parallel/test-abortcontroller.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,13 @@ const { ok, strictEqual, throws } = require('assert');
const signal = AbortSignal.abort('reason');
strictEqual(signal.reason, 'reason');
}

{
// Test AbortSignal timeout
const signal = AbortSignal.timeout(10);
ok(!signal.aborted);
setTimeout(() => {
ok(signal.aborted);
strictEqual(signal.reason.code, 23);
}, 20);
}

0 comments on commit f04a7fb

Please sign in to comment.