json
2025-11-11
fe
Description
descr
Code
{ "id": 2, "title": "Fetch with Timeout", "summary": "Enhanced fetch wrapper with configurable timeout", "description": "An enhanced fetch wrapper that adds timeout functionality to prevent requests from hanging indefinitely.\n\n**How it works:**\n1. Creates an `AbortController` to manage request cancellation\n2. Sets a timeout using `setTimeout`\n3. Aborts the request if timeout is reached\n4. Properly cleans up the timeout on completion\n\n**Benefits:**\n- Prevents application freezing from slow networks\n- Provides predictable timeout behavior\n- Graceful error handling for timeout scenarios\n- Compatible with standard Fetch API options\n\nEssential for building robust applications that handle network unreliability gracefully.", "language": { "name": "javascript", "spec": "ES2017" }, "tags": ["api", "fetch", "async", "timeout", "network"], "dependencies": [], "dateAdded": "2025-10-19", "code": "async function fetchWithTimeout(url, options = {}) {\n const timeout = ;\n \n const controller = new AbortController();\n const id = setTimeout(() => controller.abort(), timeout);\n \n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal\n });\n clearTimeout(id);\n return response;\n } catch (error) {\n clearTimeout(id);\n if (error.name === 'AbortError') {\n throw new Error('Request timeout');\n }\n throw error;\n }\n}", "parameters": [ { "name": "timeout", "label": "Timeout (ms)", "defaultValue": "5000", "type": "number" }, { "name": "apiUrl", "label": "API URL", "defaultValue": "https://api.example.com/data", "type": "text" } ], "usage": [ { "description": "Fetch data from an API with timeout", "code": "fetchWithTimeout('', { timeout: })\n .then(res => res.json())\n .then(data => console.log(data))\n .catch(err => console.error(err));" } ]}
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.