JavaScript10 linesUpdated Jul 17, 2026
JavaScript
export async function fetchWithTimeout(url, ms = 5000, options = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
const res = await fetch(url, { ...options, signal: controller.signal });
return await res.json();
} finally {
clearTimeout(timer);
}
}