QuickSnip
← Back to browse

Fetch with timeout

Abort a fetch request if it takes longer than the given timeout.

JavaScript10 linesUpdated Jul 17, 2026
Edit
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);
  }
}