Make HTTP requests with a configurable timeout using AbortController.
Code
Utilitiesconst controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
const response = await fetch(url, { signal: controller.signal })
.finally(() => clearTimeout(timeoutId));
const data = await response.json();Parameters
URL to fetch
Timeout in milliseconds
Browser·fetch() may be limited by CORS
How It Works
- AbortController - Creates a controller that can abort the fetch request
- setTimeout - Triggers
abort()after the specified timeout - signal - Pass the controller's signal to fetch to enable cancellation
- finally - Clear the timeout if fetch completes before timeout
Error Handling
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
const response = await fetch(url, { signal: controller.signal })
.finally(() => clearTimeout(timeoutId));
return await response.json();
} catch (err) {
if (err.name === 'AbortError') {
throw new Error(`Request timed out after ${timeoutMs}ms`);
}
throw err;
}
Reusable Function
async function fetchWithTimeout(url, options = {}, timeout = 5000) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(url, {
...options,
signal: controller.signal
}).finally(() => clearTimeout(timeoutId));
return response;
}
Test URLs
https://httpbin.org/delay/1- Responds after 1 secondhttps://httpbin.org/delay/5- Responds after 5 seconds (will timeout with default 3s)
More JavaScript Snippets
Add Query Parameter
Add or update a query parameter in a URL string.
Bearer Token Authentication
Make an authenticated HTTP request using Bearer token for JWT or OAuth.
Check Cloudflare Cache Status
Check if a resource is served from Cloudflare's cache by inspecting the CF-Cache-Status header.
CORS Cross-Origin Request
Make a cross-origin HTTP request with CORS headers inspection.
Delayed Response (Test Timeouts)
Request a delayed response to test timeout handling with AbortController.
Download Binary File
Download an image or binary file and convert it to a blob or base64.