CrackFrontendCF
Resources
Practice
CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❀️ by Tushar Khanna

CrackFrontendCF
Resources
Practice

πŸ›‘ AbortController: Canceling Async Operations in JavaScript

AbortController provides a standard way to cancel asynchronous operations like fetch requests. Critical for cleaning up pending operations and preventing memory leaks.

is a built-in Web API that allows you to cancel asynchronous operations, especially ones that support an , like , streams, or custom async tasks. -- πŸ’‘ Core Concepts 1. ** Creates a controller with a object. You call to cancel the operation. 2. * Passed to the async operation. Has boolean flag and emits an event. -- πŸ§ͺ Example: Cancel -- πŸ“¦ Common Use Cases How Helps βœ… Native support Custom async tasks βœ… Combine with timeouts or control logic React effects -- 🧠 Example in Custom Code Create a function that supports cancellation via . Here’s a precise, fetch-cancelable promise implementation using : -- βœ… Cancelable Fetch with AbortController -- πŸ§ͺ Example: -- βœ… Behavior: Uses to terminate the underlying request. If canceled, rejects with . Unlike , this actually stops the request . -- ⚠️ Works With: Some APIs like , , (in newer specs) -- Let me know if you want a generic wrapper that adds cancelation to any async operation (not just ). -- <!-quiz-start --Q1: What error name is thrown when a fetch request is aborted? [ ] CancelError [x] AbortError [ ] TimeoutError [ ] RequestError Q2: Which property of AbortController do you pass to fetch()? [ ] controller.abort [ ] controller.cancel [x] controller.signal [ ] controller.token Q3: What does signal.aborted return after calling abort()? [x] true [ ] false [ ] undefined [ ] "aborted" <!-quiz-end --
JavaScriptCore Concepts
πŸ›‘ AbortController: Canceling Async Operations in JavaScript
medium
πŸ”’ Closures in JavaScript β€” The Complete Guide
hard
πŸ“¦ Understanding ES6 Modules in JavaScript
medium
⚑ JavaScript Event Loop: Complete Guide to Asynchronous Execution
hard
🧭 Arrow Functions vs Function Declarations in JavaScript
easy
πŸ—‘οΈ Garbage Collection in JavaScript β€” Memory Management & Leak Prevention
hard
πŸ—οΈ Constructor Functions in JavaScript
medium
πŸ‘οΈ MutationObserver: Watching DOM Changes in JavaScript
medium
πŸ” Understanding `of` in JavaScript – `for...of` Loop Deep Dive
hard
πŸ”— Prototype and Prototype Inheritance in JavaScript
medium
πŸ•΅οΈ What Are Proxies in JavaScript? (With Practical Use Cases)
medium
🎯 Scope in JavaScript β€” The Complete Guide
hard
πŸ”„ Script Loading: async vs defer vs Both
hard
πŸ“€ JavaScript Spread Operator (...) Explained
easy
🎯 The JavaScript `this` Keyword: Complete Guide to Context Binding
medium
1 of 15
LibraryJavaScriptCore Concepts1 of 61

πŸ›‘ AbortController: Canceling Async Operations in JavaScript

jsgeneral-conceptsmedium

AbortController is a built-in Web API that allows you to cancel asynchronous operations, especially ones that support an AbortSignal, like fetch, streams, or custom async tasks.


πŸ’‘ Core Concepts

1. AbortController

  • Creates a controller with a .signal object.
  • You call .abort() to cancel the operation.

2. AbortSignal

  • Passed to the async operation.
  • Has .aborted boolean flag and emits an abort event.

πŸ§ͺ Example: Cancel fetch

const controller = new AbortController();
const signal = controller.signal;

fetch('https://api.example.com/data', { signal })
  .then(res => res.json())
  .then(console.log)
  .catch(err => {
    if (err.name === 'AbortError') console.log('Fetch canceled');
    else console.error(err);
  });

// Cancel after 100ms
setTimeout(() => controller.abort(), 100);

πŸ“¦ Common Use Cases

Use CaseHow AbortControllerHelps
fetch()cancellationβœ… Native support
Custom async tasksβœ… Add your own signal checks
Debounce, retry, raceβœ… Combine with timeouts or control logic
React effectsβœ… Cleanup async ops on unmount

🧠 Example in Custom Code

Create a wait(ms) function that supports cancellation via AbortController.

function wait(ms, signal) {
  return new Promise((resolve, reject) => {
    const timeout = setTimeout(() => resolve("done"), ms);
    signal?.addEventListener("abort", () => {
      clearTimeout(timeout);
      reject(new DOMException("Aborted", "AbortError"));
    });
  });
}

Here’s a precise, fetch-cancelable promise implementation using AbortController :


βœ… Cancelable Fetch with AbortController

function fetchWithCancel(url, options = {}) {
  const controller = new AbortController();
  const signal = controller.signal;

  const fetchPromise = fetch(url, { ...options, signal });

  return {
    promise: fetchPromise,
    cancel: () => controller.abort()
  };
}

πŸ§ͺ Example:

const { promise, cancel } = fetchWithCancel('https://jsonplaceholder.typicode.com/posts/1');

promise
  .then(res => res.json())
  .then(data => console.log('Fetched:', data))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch canceled');
    } else {
      console.error('Error:', err);
    }
  });

// Cancel after 100ms
setTimeout(cancel, 100);

βœ… Behavior:

  • Uses AbortController to terminate the underlying fetch request.
  • If canceled, fetch rejects with AbortError.
  • Unlike makeCancelable, this actually stops the request .

⚠️ Works With:

  • fetch
  • Some APIs like ReadableStream, Request, WebSocket (in newer specs)

Let me know if you want a generic wrapper that adds cancelation to any async operation (not just fetch).


Quick Quiz

Test your understanding with 3 quick questions

Q1What error name is thrown when a fetch request is aborted?
Q2Which property of AbortController do you pass to fetch()?
Q3What does signal.aborted return after calling abort()?

Continue Reading

CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❀️ by Tushar Khanna