I have an array with some values that should be passed as parameter to a api call. I want to update data with results from the api call. And I want to call the api every 1 second with each value of the array.
example :
const people = [1, 2, 3, 4, 5];
people.forEach((person, index) => {
setTimeout(() => {
fetch(`https://swapi.dev/api/people/${person}/`)
.then(res => res.json())
.then(data => {
// do stuff, eg : update UI
console.log(data.name);
})
}, index * 1000);
});
Since I want to keep calling the api and keep updating data or UI, is wrapping the forEach() in a infinite loop a good idea, like this :
while(true) {
people.forEach((person, index) => {
setTimeout(() => {
fetch(`https://swapi.dev/api/people/${person}/`)
.then(res => res.json())
.then(data => {
// do stuff, eg : update UI
console.log(data.name) ;
})
}, index * 1000);
}) ;
} ;
if it's a bad idea please mention why and suggest other methods to do it right. Thanks in advance.
Bit more info :- The api I want to use has a rate limit of 100 api calls per 5 seconds, So I will have to call it every 3 seconds to keep it real time without hitting the limit.
Each array element is different endponts so it needs to be iterated completely to keep the data as real time as possible.
this script is supposed to run 24/7 to update the data
the starwars api is just used as an example because that was the first one that came into my mind.
This was originally provided by @Chris G
This one is working like a charm
const people = [1, 2, 3, 4, 5];
function apiCall(person) {
fetch(`https://swapi.dev/api/people/${person}/`)
.then(res => res.json())
.then(data => {
// do stuff, eg : update UI
console.log(data.name);
});
}
people.forEach((person, index) => {
setTimeout(() => {
apiCall(person);
setInterval(() => {
apiCall(person);
}, people.length * 1000);
}, index * 1000);
});
Just because I took sometime to understand how the above code works, I'm gonna provide some detail below :
The forEach loop executed and exited but while executing it triggered the setTimeouts, and when the setTimeouts ran it triggered the setIntervals. And all of those actually ran outside forEach loop but was able to access the variables because of closure