Using AbortController Beyond Fetch
You'll learn how to apply AbortController and AbortSignal to event listeners, timers, and custom async functions for unified cancellation across your entire application.
Beyond Network Requests
While AbortController was designed for fetch cancellation, its signal pattern works beautifully for any cancelable operation. Think of AbortSignal as a universal "stop button" that different parts of your code can listen to.
Canceling Event Listeners
You can pass the signal directly to addEventListener to auto-remove the listener when aborted:
const controller = new AbortController();
document.addEventListener('click', handleClick, {
signal: controller.signal
});
// Later: removes the listener automatically
controller.abort();
Wrapping setTimeout
Create a cancelable timer by checking the signal inside a promise:
function delay(ms, signal) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(resolve, ms);
signal.addEventListener('abort', () => {
clearTimeout(timeout);
reject(new DOMException('Aborted', 'AbortError'));
});
});
}
const controller = new AbortController();
delay(5000, controller.signal).catch(err => console.log(err.name)); // AbortError
controller.abort();
Custom Async Functions
Any long-running operation can accept a signal and periodically check signal.aborted:
async function processItems(items, signal) {
for (const item of items) {
if (signal.aborted) {
throw new DOMException('Aborted', 'AbortError');
}
await doWork(item);
}
}
Key Takeaway: AbortController provides a standard cancellation pattern that works across events, timers, and custom async code—not just fetch—giving you consistent control over any cancelable operation in your application.