惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
博客园_首页
Vercel News
Vercel News
WordPress大学
WordPress大学
美团技术团队
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Y
Y Combinator Blog
博客园 - 【当耐特】
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
腾讯CDC
M
MIT News - Artificial intelligence
爱范儿
爱范儿
Recent Announcements
Recent Announcements
雷峰网
雷峰网
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
Jina AI
Jina AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
P
Privacy & Cybersecurity Law Blog
Recorded Future
Recorded Future
Help Net Security
Help Net Security
N
News and Events Feed by Topic
博客园 - Franky
P
Proofpoint News Feed
L
LINUX DO - 热门话题
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
D
Docker
Google DeepMind News
Google DeepMind News
有赞技术团队
有赞技术团队
IT之家
IT之家
Security Latest
Security Latest
L
LangChain Blog
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
J
Java Code Geeks

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Timeout a fetch() Request
Dmitri Pavlutin · 2020-10-27 · via Dmitri Pavlutin Blog
Post cover

You should not rely on the network when working with it. The network is unreliable because an HTTP request or response can fail:

  • The user is offline
  • DNS lookup failed
  • The server doesn't respond
  • The server responds but with an error
  • and more.

Users are OK to wait up to 8 seconds for simple requests to complete. That's why you need to set a timeout on the network requests and inform the user after 8 seconds about the network problems.

I'll show you how to use setTimeout(), the abort controller, and fetch() to implement configurable request timeouts.

1. Default fetch() timeout

By default a fetch() request timeouts at the time indicated by the browser. In Chrome a network request timeouts at 300 seconds, while in Firefox at 90 seconds.


async function loadGames() {

const response = await fetch('/games');

// fetch() timeouts at 300 seconds in Chrome

const games = await response.json();

return games;

}


300 seconds and even 90 seconds are way more than a user would expect a network request to complete.

As an experiment, in the demo the /games API response takes 301 seconds. Click Load games button to start the request, and it will timeout at 300 seconds (in Chrome).

2. Timeout a fetch() request

fetch() API by itself doesn't allow canceling programmatically a request. To stop a request at the desired time you also need an abort controller.

The following fetchWithTimeout() is an improved version of fetch() that creates requests with a configurable timeout:


async function fetchWithTimeout(resource, options = {}) {

const { timeout = 8000 } = options;

const controller = new AbortController();

const id = setTimeout(() => controller.abort(), timeout);

const response = await fetch(resource, {

...options,

signal: controller.signal

});

clearTimeout(id);

return response;

}


First, const { timeout = 8000 } = options extracts the timeout param in milliseconds from the options object (defaults to 8 seconds).

const controller = new AbortController() creates an instance of the abort controller. This controller allows you stop fetch() requests at will. A new abort controller must be created for each request, in other words, controllers aren't reusable.

const id = setTimeout(() => controller.abort(), timeout) starts a timing function. After timeout time, if the timing function wasn't cleared, controller.abort() cancels the fetch request.

Next line await fetch(resource, { ...option, signal: controller.signal }) starts properly the fetch request. Note the special controller.signal value assigned to signal property: it connectes fetch() with the abort controller.

Finally, clearTimeout(id) clears the abort timing function if the request completes earlier than timeout time passed.

Now here's how to use fetchWithTimeout():


async function loadGames() {

try {

const response = await fetchWithTimeout('/games', {

timeout: 6000

});

const games = await response.json();

return games;

} catch (error) {

// Timeouts if the request takes

// longer than 6 seconds

console.log(error.name === 'AbortError');

}

}


Open the demo.

fetchWithTimeout() (instead of simple fetch()) starts a request that will be canceled at timeout time — 6 seconds.

If the request to /games hasn't finished in 6 seconds, then the request is canceled and a timeout error is thrown.

You can use the expression error.name === 'AbortError' inside the catch block to determine if there was a request timeout.

Open the demo and click Load games button. The request to /games timeouts because it takes longer than 6 seconds.

3. AbortSignal.timeout()

Current browsers support a simpler approach using AbortSignal.timeout():


async function loadGames() {

try {

const response = await fetch('/games', {

signal: AbortSignal.timeout(5000)

});

const games = await response.json();

return games;

} catch (error) {

// Timeouts if the request takes

// longer than 6 seconds

console.log(error.name === 'AbortError');

}

}


4. Summary

By default a fetch() request timeouts at the time set up by the browser. In Chrome, for example, this setting is 300 seconds. That's way longer than a user would expect for a network request to complete.

A good approach to network requests is to configure a request timeout of about 8 - 10 seconds.

Using setTimeout() and abort controller you can create fetch() requests that are configured to timeout when you'd like to.

Check the browser support for the abort controller. There's also a polyfill for it.

Note that there's no way to stop a fetch() request without using an abort controller. Don't use solutions like this.

What good practices regarding network requests do you know? Please write a comment!

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉, developing a gift boxes Shopify app, and blogging about Shopify. Living in the sunny Barcelona. 🇪🇸