ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

AJAX & Fetch API Tutorial• 6 min read

Request Cancellation & Timeouts with AbortController

Cancelling stale search auto-complete requests and enforcing timeouts

The AbortController API allows you to abort in-flight fetch requests, essential for cancelling stale search autocomplete queries and enforcing strict client-side timeouts.

Using AbortController and Signals

Create a controller: const controller = new AbortController().

Pass its signal to fetch: fetch(url, { signal: controller.signal }).

Cancel anytime: Calling controller.abort() immediately cancels the HTTP request and rejects the promise with an AbortError.

Modern Timeout Helper: AbortSignal.timeout(5000) automatically aborts after 5 seconds.

Enforcing a 5-Second Timeout on Fetch
async function fetchWithTimeout(resource, timeoutMs = 5000) {
  try {
    const response = await fetch(resource, {
      signal: AbortSignal.timeout(timeoutMs) // Native 5-second abort
    });
    return await response.json();
  } catch (error) {
    if (error.name === "TimeoutError") {
      console.error("Request aborted due to timeout!");
    } else {
      console.error("Fetch failed:", error.message);
    }
  }
}
Prevents applications from hanging indefinitely on stalled networks.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which native API allows cancelling an in-flight `fetch()` request or enforcing timeouts?