Network Requests
Abort Controller Timeout
AbortController creates a signal that can cancel a slow fetch and route the UI into a timeout state.
Program
Network requests can be too slow. AbortController gives client code a cancellation signal that fetch understands.
abort_controller_timeout.html
<output id="status">Loading report</output>
<script>
const statusEl = document.querySelector("#status");
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 2000);
fetch("/api/report", { signal: controller.signal })
.then(() => statusEl.textContent = "Report loaded")
.catch(error => statusEl.textContent = error.name === "AbortError" ? "Timed out" : "Failed")
.finally(() => clearTimeout(timeoutId));
</script>
AbortController
AbortController creates a signal used to cancel async work.
finally
A Promise finally handler runs after success or failure for cleanup.