JavaScript Course
JavaScript
/
Advanced

AbortController (JS)

Definition

A DOM API that allows you to abort one or more Web requests (like `fetch`) or event listeners as and when desired.

Explain Like I'm New

When you call a function that takes a long time, sometimes you change your mind and want to cancel it. AbortController gives you a 'Kill Switch' remote control. You pass the remote's receiver (`signal`) to the fetch request, and press the big red button (`abort()`) when you want to stop it.

Real World Example

A user clicks 'Generate Heavy Report' but then immediately clicks 'Cancel'. You use AbortController to kill the fetch request so the browser doesn't waste bandwidth downloading a 50MB file the user no longer wants.

Common Use Cases

  • •Canceling fetch requests
  • •Removing multiple event listeners at once

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What are the two parts of the AbortController?

intermediate

  • What happens to the Promise returned by `fetch` when it is aborted?

advanced

  • Can you use AbortController to cancel a standard `setTimeout`?

Flash Cards

Question

What are the two parts?

Click to reveal answer
Answer

The `controller` itself (which holds the `abort()` method), and the `controller.signal` (which is passed into the fetch options to link them together).

Question

Can you cancel a setTimeout?

Click to reveal answer
Answer

Not natively, but you can build a wrapper. However, Node.js recently added `AbortSignal` support to its native timers (`setTimeout(cb, 1000, { signal })`). In the browser, you must listen for the `signal.addEventListener('abort', ...)` and call `clearTimeout` manually.