patternjavascriptModeratepending
JavaScript AbortController for cancellable operations
Viewed 0 times
abort controllercancel fetchabort signaltimeoutcancellation
Problem
Need to cancel in-flight fetch requests, timeouts, or other async operations.
Solution
AbortController works with fetch, event listeners, and custom async operations:
// Cancel fetch requests
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal })
.then(r => r.json())
.catch(err => {
if (err.name === 'AbortError') {
console.log('Request cancelled');
}
});
// Cancel after timeout
controller.abort(); // Cancels the fetch
// Timeout pattern
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
// Or use AbortSignal.timeout (modern browsers)
fetch('/api/data', { signal: AbortSignal.timeout(5000) });
// Combine signals
const controller = new AbortController();
const timeoutSignal = AbortSignal.timeout(5000);
const combined = AbortSignal.any([controller.signal, timeoutSignal]);
fetch('/api/data', { signal: combined });
// With event listeners
const controller = new AbortController();
element.addEventListener('click', handler, { signal: controller.signal });
// Later: removes the listener
controller.abort();Why
AbortController provides a standard way to cancel async operations, preventing memory leaks and wasted network requests.
Context
Web applications with cancellable network requests or event listeners
Revisions (0)
No revisions yet.