Timeouts & Aborting with AbortController
Add timeouts to async code and cancel work with AbortController; wire signals into tasks to stop early.
Why timeouts and aborts?
Goal: Stop long tasks safely.
- Add a simple timeout
- Use AbortController
- Wire signal to your task
- Clean up timers

Signal-aware task
Create tasks that listen to signal.abort and stop the timer on cancel.
// Fake fetch that respects AbortSignal
function fakeFetch(ms, value, signal) {
return new Promise(function (resolve, reject) {
// Abort handler
function onAbort() {
clearTimeout(t);
reject(new Error("aborted"));
}
// If already aborted
if (signal && signal.aborted) {
return reject(new Error("aborted"));
}
// Finish timer
const t = setTimeout(function () {
if (signal) {
signal.removeEventListener("abort", onAbort);
}
resolve(value);
}, ms);
// Listen for abort
if (signal) {
signal.addEventListener("abort", onAbort);
}
});
}
fakeFetch(5, "OK").then(function (v) {
console.log("fakeFetch:", v);
});

All lessons in this course
- Writing async functions; try/catch; parallel vs sequential
- Timeouts & Aborting with AbortController
- Retrying & Backoff Patterns