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 <jasnell@gmail.com>
  • Loading branch information
jasnell committed Nov 24, 2021
1 parent 7633c86 commit 820e505
Show file tree
Hide file tree
Showing 3 changed files with 50 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
11 changes: 11 additions & 0 deletions test/parallel/test-abortcontroller.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,14 @@ 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(common.mustCall(() => {
ok(signal.aborted);
strictEqual(signal.reason.name, 'TimeoutError');
strictEqual(signal.reason.code, 23);
}), 20);
}

0 comments on commit 820e505

Please sign in to comment.