Give up after a timeout

fetch waits forever by default. Add your own limit.

AJAX · Give up after a timeoutIntermediate
async function fetchWithTimeout(url, ms = 8000, options = {}) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), ms);
  try {
    return await fetch(url, { ...options, signal: controller.signal });
  } catch (err) {
    if (err.name === 'AbortError') throw new Error('Request timed out after ' + ms + ' ms');
    throw err;
  } finally {
    clearTimeout(timer);
  }
}
timeoutabortAbortControllerfetch