I would like to know if there is a way that if my request takes more than 20 seconds, I can show an alert alerting users of an error in the API. So they can refresh the page or come back later.
Something like response.status.
I do NOT need setTimeout and AbortController. Just detect response and trigger the alert.
JavaScript
x
49
49
1
const envSoli = async () => {
2
try {
3
let peticion = await fetch("data.php", {
4
method: "POST",
5
body: "ajax=1&do=check&lista=" + encodeURIComponent(leray[chenille]),
6
headers: { "Content-type": "application/x-www-form-urlencoded" },
7
cache: "no-cache"
8
});
9
let oreen = await peticion.json();
10
11
switch (oreen.enviando) {
12
case -1:
13
chenille++;
14
document.getElementById("div1").append(oreen.cat + "<br />");
15
updateProgress(chenille, leray.length);
16
tvmit_wrongUp();
17
break;
18
19
case 1:
20
chenille++;
21
document.getElementById("div1").append(oreen.dog + "<br />");
22
updateProgress(chenille, leray.length);
23
tvmit_wrongUp();
24
break;
25
26
case 2:
27
chenille++;
28
document.getElementById("div2").append(oreen.sky + "<br />");
29
nieva++;
30
updateProgress(chenille, leray.length);
31
tvmit_dieUp();
32
break;
33
34
case 3:
35
chenille++;
36
document.getElementById("div3").append(oreen.water + "<br />");
37
tvmit_liveUp();
38
updateProgress(chenille, leray.length);
39
break;
40
}
41
42
OKTY(leray, chenille, aarsh, nieva);
43
return true;
44
} catch (error) {
45
console.log(error)
46
}
47
}
48
envSoli();
49
Advertisement
Answer
You need setTimeout
to set the timer
to 20 sec, and after the fetch
request, if the request takes less than 20 seconds, clear the timeout
JavaScript
1
52
52
1
const envSoli = async () => {
2
try {
3
let timeId = setTimeout(() => alert('The request take more than 20 sec'), 20 * 1000); // 20 sec
4
let peticion = await fetch("data.php", {
5
method: "POST",
6
body: "ajax=1&do=check&lista=" + encodeURIComponent(leray[chenille]),
7
headers: { "Content-type": "application/x-www-form-urlencoded" },
8
cache: "no-cache"
9
});
10
clearTimeout(timeId)
11
let oreen = await peticion.json();
12
13
switch (oreen.enviando) {
14
case -1:
15
chenille++;
16
document.getElementById("div1").append(oreen.cat + "<br />");
17
updateProgress(chenille, leray.length);
18
tvmit_wrongUp();
19
break;
20
21
case 1:
22
chenille++;
23
document.getElementById("div1").append(oreen.dog + "<br />");
24
updateProgress(chenille, leray.length);
25
tvmit_wrongUp();
26
break;
27
28
case 2:
29
chenille++;
30
document.getElementById("div2").append(oreen.sky + "<br />");
31
nieva++;
32
updateProgress(chenille, leray.length);
33
tvmit_dieUp();
34
break;
35
36
case 3:
37
chenille++;
38
document.getElementById("div3").append(oreen.water + "<br />");
39
tvmit_liveUp();
40
updateProgress(chenille, leray.length);
41
break;
42
}
43
44
OKTY(leray, chenille, aarsh, nieva);
45
return true;
46
} catch (error) {
47
console.log(error)
48
}
49
}
50
envSoli();
51
52