I am building a small prototype like feeds. I have an array of many items. For each item in an array, I need to make an API call and load results.
It's a performance issue if I have too many records and too many APi calls to make.
I am trying to stop my loop for every 2-3 API calls for 100ms and then resume execution till array is completed.
I made a POC but it doesn't work well. Can you help me with whats wrong in below code
// work in progress
var arr = ["val1", "val2", "val3", "val4", "val5", "val6"];
let breakCounter;
async function seriesAPI(arr) {
breakCounter = 2;
for (let i = 0; i <= arr.length; i++) {
if (breakCounter - arr.indexOf(arr[i]) === 0) {
await interval(arr[i]);
breakCounter = breakCounter + 2;
} else {
makeAPI(arr[i])
//console.log(arr[i]);
}
}
}
function makeAPI(val) {
console.log(val);
// fetch(url, {method: 'POST', body: JSON.stringify(arr[i])}).then(res => console.log(res));
}
function interval(arrval) {
console.log("Buffer time");
setTimeout(() => {
makeAPI(arrval)
}, 1000);
}
seriesAPI(arr);
I suggest you to wrap your interval method as Promise and call it on loop iteration when it's needed before request fetching.
var arr = ["val1", "val2", "val3", "val4", "val5", "val6"];
async function seriesAPI(arr) {
for (let i = 0; i <= arr.length; i++) {
if (!(i % 3)) { // on each 3rd iteration
await interval(100); // make 100ms delay
}
makeAPI(arr[i])
// console.log(arr[i]);
}
}
function makeAPI(val) {
console.log(val);
// fetch(url, {method: 'POST', body: JSON.stringify(arr[i])}).then(res => console.log(res));
}
function interval(ms) {
return new Promise(r => setTimeout(r, ms));
// auto-resolve after [ms] milliseconds
}
seriesAPI(arr);
No need for async
var arr = ["val1", "val2", "val3", "val4", "val5", "val6"];
let cnt = 0;
function makeAPI() {
if (cnt >= arr.length) return
console.log(arr[cnt]);
// fetch(url, {method: 'POST', body: JSON.stringify(arr[cnt])})
// .then(res => setTimeout(makeAPI,cnt%3 === 0 ? 3000: 100));
cnt++;
setTimeout(makeAPI,cnt%3 === 0 ? 3000: 100);
}
makeAPI()