// Created on savesnippets.com ยท https://savesnippets.com/2syFiadkwIxlZD async function fetchRetry(url, options = {}, retries = 3, backoff = 300) { for (let i = 0; i < retries; i++) { try { const res = await fetch(url, options); if (res.ok) return res; if (res.status < 500) throw new Error(`HTTP ${res.status}`); // don't retry 4xx } catch (err) { if (i === retries - 1) throw err; } await new Promise((r) => setTimeout(r, backoff * 2 ** i)); } } // Usage const res = await fetchRetry('/api/data', {}, 3, 500); const data = await res.json();