🚦 AbortSignal represents a signal object that allows you to communicate with a DOM request and abort it if required via an AbortController.

Think of it as a magical redstone signal that can stop things!

// Create a signal that automatically aborts after 5 seconds
const signal = AbortSignal.timeout(5000);

async function longRunningTask(signal: AbortSignal) {
while(true) {
signal.throwIfAborted(); // Will throw after 5 seconds
// Do some work...
await sleep(100);
}
}

Constructors

Properties

onabort: null | () => void = null

Accessors

  • get aborted(): boolean
  • Returns boolean

  • get reason(): any
  • Returns any

Methods

  • Adds an event listener for the abort event.

    Parameters

    • listener: (event: { type: "abort" }) => void

      Function to call when the signal is aborted

    • Optionaloptions: { once?: boolean }

      Listener options (currently only supports 'once')

    Returns void

    signal.addEventListener(() => {
    print("Signal was aborted!");
    }, { once: true });
  • Parameters

    • Optional_event: "abort"

    Returns void

  • Returns void

  • Creates an AbortSignal that is already aborted.

    Parameters

    • Optionalreason: any

      The abort reason (like "timeout" or "user cancelled")

    Returns AbortSignal

    A pre-aborted AbortSignal

    // Create an already aborted signal
    const signal = AbortSignal.abort("Operation cancelled");

    // This will throw immediately
    signal.throwIfAborted(); // throws "Operation cancelled"
  • Combines multiple AbortSignals into one. If any of the input signals abort, the resulting signal will also abort.

    Parameters

    • signals: AbortSignal[]

      Array of AbortSignals to combine

    Returns AbortSignal

    A new AbortSignal that aborts when any input signal aborts

    // Abort if either 5 seconds pass OR user cancels
    const timeoutSignal = AbortSignal.timeout(5000);
    const userSignal = new AbortController().signal;

    const combinedSignal = AbortSignal.any([timeoutSignal, userSignal]);
  • Creates an AbortSignal that automatically aborts after the specified delay. Perfect for implementing timeouts!

    Parameters

    • delay: number

      Time in milliseconds before the signal aborts

    Returns AbortSignal

    An AbortSignal that will abort after the delay

    When the timeout expires

    // Create a signal that aborts after 5 seconds
    const signal = AbortSignal.timeout(5000);

    try {
    await doLongTask(signal);
    } catch (e) {
    print("Task timed out!");
    }