JavaScript Academy · Lesson

Timeouts & Aborting with AbortController

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

Lesson 2 of 38 steps

Timeouts & Aborting with AbortController is a free JavaScript Academy lesson on CoddyKit. This is lesson 2 of 3. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, and your progress syncs across the web and the CoddyKit app. The JavaScript Academy course includes 3 lessons in total.

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

Abort in action

Create a controller, pass its signal, and call abort() to cancel.

// AbortController cancels signal-aware tasks
const controller = new AbortController();

fakeFetch(20, "Too slow", controller.signal)
  .then(function (v) {
    console.log("done:", v);
  })
  .catch(function (e) {
    console.log("catch:", e.message);
  });

// Abort after a short delay
setTimeout(function () {
  controller.abort();
  console.log("aborted");
}, 5);
Timeouts & Aborting with AbortController — illustration 3

Timeout wrapper

Use Promise.race to reject if the task takes too long; clear the timer in finally.

// Add a timeout to any Promise with Promise.race
function withTimeout(promise, ms) {
  return Promise.race([
    promise,
    new Promise(function (_resolve, reject) {
      const t = setTimeout(function () {
        reject(new Error("timeout"));
      }, ms);
      // Small trick: clear timer when the main promise settles
      promise.finally(function () { clearTimeout(t); });
    })
  ]);
}

// Demo: this will time out
withTimeout(fakeFetch(30, "late"), 10)
  .then(function (v) { console.log("value:", v); })
  .catch(function (e) { console.log("timeout:", e.message); });
Timeouts & Aborting with AbortController — illustration 4

Timeout + abort together

If the timeout wins, call abort() so the underlying work stops early.

// Combine: abort if timeout fires
async function fetchWithTimeout(msWork, msTimeout) {
  const c = new AbortController();

  const task = fakeFetch(msWork, "data", c.signal);

  // If timeout wins, abort the task
  try {
    const result = await withTimeout(task, msTimeout);
    return result;
  } catch (e) {
    c.abort();
    throw e;
  }
}

fetchWithTimeout(25, 10)
  .then(function (v) { console.log("got:", v); })
  .catch(function (e) { console.log("failed:", e.message); });
Timeouts & Aborting with AbortController — illustration 5

Tips & checklist

Tips:

  • Always clear timers in finally.
  • Pass signal into tasks and check signal.aborted.
  • Prefer one controller per request.
Timeouts & Aborting with AbortController — illustration 6

AbortController basics quiz

Quick check: Cancel pattern.

Timeouts & Aborting with AbortController — illustration 7

Recap

Recap: You built a signal-aware task, canceled it with AbortController, added a timeout via Promise.race, and combined both for safe early exits.

Timeouts & Aborting with AbortController — illustration 8
Free to start

Learn JavaScript with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
59
Lessons
200

Frequently Asked Questions

Is the “Timeouts & Aborting with AbortController” lesson free?

Yes — any 3 lessons of the JavaScript Academy learning path, including “Timeouts & Aborting with AbortController”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The JavaScript Academy course includes 3 lessons in total.

What will I learn in “Timeouts & Aborting with AbortController”?

Add timeouts to async code and cancel work with AbortController; wire signals into tasks to stop early. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start JavaScript Academy?

No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 3.

How long does the “Timeouts & Aborting with AbortController” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this JavaScript Academy lesson?

Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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