0Pricing
JavaScript Academy · Lesson

Timeouts & Aborting with AbortController

Add timeouts to async code and cancel work with AbortController; wire signals into tasks to stop early.

Why timeouts and aborts?

Goal: Stop long tasks safely.

  • Add a simple timeout
  • Use AbortController
  • Wire signal to your task
  • Clean up timers
Timeouts & Aborting with AbortController — illustration 1

Signal-aware task

Create tasks that listen to signal.abort and stop the timer on cancel.

// Fake fetch that respects AbortSignal
function fakeFetch(ms, value, signal) {
  return new Promise(function (resolve, reject) {
    // Abort handler
    function onAbort() {
      clearTimeout(t);
      reject(new Error("aborted"));
    }

    // If already aborted
    if (signal && signal.aborted) {
      return reject(new Error("aborted"));
    }

    // Finish timer
    const t = setTimeout(function () {
      if (signal) {
        signal.removeEventListener("abort", onAbort);
      }
      resolve(value);
    }, ms);

    // Listen for abort
    if (signal) {
      signal.addEventListener("abort", onAbort);
    }
  });
}

fakeFetch(5, "OK").then(function (v) {
  console.log("fakeFetch:", v);
});
Timeouts & Aborting with AbortController — illustration 2

All lessons in this course

  1. Writing async functions; try/catch; parallel vs sequential
  2. Timeouts & Aborting with AbortController
  3. Retrying & Backoff Patterns
← Back to JavaScript Academy