Skip to content

Commit bc042c8

Browse files
authored
Create fetchURLsWithDelay.js
Call a function where two (2) URLs in an array variable and fetch these URLs with a gap of 1 second
1 parent 05f81b2 commit bc042c8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function fetchURLsWithDelay(urls) {
2+
let index = 0;
3+
4+
function fetchNext() {
5+
if (index < urls.length) {
6+
fetch(urls[index])
7+
.then(response => {
8+
if (!response.ok) {
9+
throw new Error('Network response was not ok');
10+
}
11+
return response.json();
12+
})
13+
.then(data => {
14+
console.log('Data fetched:', data);
15+
index++;
16+
setTimeout(fetchNext, 1000); // 1000 milliseconds = 1 second
17+
})
18+
.catch(error => {
19+
console.error('Error fetching data:', error);
20+
index++;
21+
setTimeout(fetchNext, 1000); // Move to next URL even if there's an error
22+
});
23+
}
24+
}
25+
26+
fetchNext();
27+
}
28+
29+
// Example usage:
30+
const urls = ['https://example.com/url1', 'https://example.com/url2'];
31+
fetchURLsWithDelay(urls);

0 commit comments

Comments
 (0)