Você está em boa companhia com suporte incrível 🤝

Fetch com timeout e retry

Wrapper para fetch com suporte a timeout configurável e retentativas automáticas.

Time Full Services Time Full Services
JavaScript
async function fetchComTimeout(url, opcoes = {}, tentativas = 3, timeoutMs = 5000) {
  for (let i = 0; i < tentativas; i++) {
    const controller = new AbortController();
    const timeout    = setTimeout(() => controller.abort(), timeoutMs);

    try {
      const resposta = await fetch(url, { ...opcoes, signal: controller.signal });
      clearTimeout(timeout);

      if (!resposta.ok) throw new Error(`HTTP ${resposta.status}`);

      return await resposta.json();
    } catch (erro) {
      clearTimeout(timeout);
      if (i === tentativas - 1) throw erro;
      await new Promise(r => setTimeout(r, 500 * (i + 1))); // backoff
    }
  }
}

// Uso:
const dados = await fetchComTimeout('/api/produtos', { method: 'GET' });

Seja PRO.

Tenha acesso a snippets de código premium — PHP, JavaScript, CSS e HTML prontos para usar em seus projetos.

Conhecer o plano Pro →