Fetch Timeouts and Retries: Make Read Requests Predictable
Practical Web Development — Lesson 6 of 10 · Intermediate A loading spinner needs an exit path. A network request can stall, fail before a response arrives or return an HTTP error. This tutorial adds a per-attempt timeout and at most one retry for a read-only JSON request. It deliberately does not retry writes such as enrolment payments or progress changes. Build a bounded read helper Put this function in a browser module. Call it with a public same-origin JSON endpoint. A local test server with a delayed endpoint is useful for exercising timeout behaviour. async function readJson(url, timeoutMs = 5000) { for (let attempt = 0; attempt < 2; attempt++) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); let retry = false; try { const response = await fetch(url, { signal: controller.signal }); if (!response.ok) { const error = new Error('HTTP ' + response.status); error.retry...