-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFetchWithTimeout.js
More file actions
54 lines (52 loc) · 1.32 KB
/
FetchWithTimeout.js
File metadata and controls
54 lines (52 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const fetchWithTimeout = function (url, delay) {
return new Promise((resolve, reject) => {
const intervalId = setInterval(() => {
fetch(url)
.then((response) => {
clearInterval(intervalId);
clearTimeout(timeId);
resolve(response);
})
.catch((reject) => {
clearInterval(intervalId);
clearTimeout(timeId);
reject("error");
});
}, delay);
const timeId = setTimeout(() => {
clearInterval(intervalId);
reject("time has taken more");
}, delay + 1);
});
};
const fetchWithTimeout1 = function (url, delay) {
return new Promise((resolve, reject) => {
const abortController = new AbortController();
const signal = abortController.signal;
fetch(url, { signal })
.then((response) => {
response
.json()
.then((data) => {
clearTimeout(timeOutId);
resolve(data);
})
.catch((e) => {
reject(e);
});
})
.catch((e) => {
reject(e);
});
const timeOutId = setTimeout(() => {
abortController.abort();
}, delay);
});
};
fetchWithTimeout("https://jsonplaceholder.typicode.com/todos/1", 1000)
.then((resp) => {
console.log(resp);
})
.catch((error) => {
console.log(error);
});