Open
Description
As a complement to the new AbortSignal.timeout()
, there are a couple more cases that may be worthwhile exploring, specifically with AbortController
:
-
abortController.timeout(delay[, reason])
- Sets an internal timer on the
AbortController
to trigger theAbortSignal
withreason
afterdelay
milliseconds. - If there is already an active internal timer, when
timeout()
is called, it is reset. - If
abortController.abort()
is directly called while there is an active internal timer, the signal is immediately triggered and the internal timer is cleared. - This is useful for implementing an ongoing "idle timeout" mechanism (e.g. the timer is reset whenever there is new activity but the signal is triggered when activity is not frequent enough).
- Sets an internal timer on the
-
abortController.cancel()
- Signals that the
AbortController
is no longer expected to trigger theAbortSignal
at all, allowing the AbortSignal to clear it's'abort'
algorithms and indicating that it is expected to never trigger. This can be used as a signal that consuming code can safely ignore the signal after it becomes abandoned. - If called while there is an active internal timeout from
abortController.timeout()
, the internal timer is cleared.
- Signals that the
Example:
const idleAborter = new AbortController();
// Controller is expected to trigger after 10 seconds
idleAborter .timeout(10_000);
const eventTarget = getSomeKindOfEventTarget({ signal: idleAborter .signal });
// Getting some kind of activity resets the internal timeout
eventTarget.addEventListener('activity', () => idleAborter.timeout(10_000));
// Signal that paying attention to the signal is no longer necessary and clears the timeout.
eventTarget.addEventListener('end', () => idleAborter.cancel());