Aller au contenu principal

3 formations sont désormais disponibles : Python, Flask et JS.

Aller au contenu principal

Fetch API avec timeout en JavaScript

Wrapper pour l'API Fetch native avec gestion du timeout via AbortController pour éviter les requêtes infinies.

Langage

javascript

Accès

Libre

/**
 * Fetch with timeout support using AbortController
 * @param {string} url - URL to fetch
 * @param {object} options - Fetch options
 * @param {number} timeout - Timeout in milliseconds
 */
async function fetchWithTimeout(url, options = {}, timeout = 5000) {
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);

  try {
    const response = await fetch(url, {
      ...options,
      signal: controller.signal,
    });
    clearTimeout(id);
    return response;
  } catch (error) {
    clearTimeout(id);
    throw error;
  }
}

Plus de snippets javascript