Senior LevelJavaScript & TypeScript
How does AbortController and AbortSignal work for canceling fetch requests and async tasks?
❓ Interview Prompt: Explain AbortController, AbortSignal events, signal timeouts, and canceling async operations.
AbortController is a standard Web API mechanism for canceling ongoing asynchronous operations (like fetch() network requests, event listeners, or custom promises).
Components:
•
`controller = new AbortController()`: Creates controller instance.
•
`controller.signal`:
AbortSignal object passed to async targets.•
`controller.abort(reason)`: Triggers the abort signal, throwing an
AbortError in the targets.•
`AbortSignal.timeout(ms)`: Auto-aborts after specified milliseconds.
Code Implementation Example
typescript
// Canceling fetch request on timeout
async function fetchWithTimeout(url: string, timeoutMs: number) {
// Built-in auto-timeout signal (Modern Web API)
const signal = AbortSignal.timeout(timeoutMs);
try {
const response = await fetch(url, { signal });
return await response.json();
} catch (err: any) {
if (err.name === 'AbortError') {
console.error('Request timed out and was aborted!');
}
throw err;
}
}💡Canceling pending fetch requests using AbortSignal.timeout.
🎯 Interview Key Takeaway
Pass AbortSignal to fetch and async tasks to allow instant cancellation and prevent resource leaks on unmounted UI.
#AbortController#AbortSignal#Async#Senior
Back to all JavaScript & TypeScript Questions→