Recently, I encountered a challenge with my JavaScript array that holds 40 items. My goal was to develop a function capable of cycling through each item in the array and initiating an API call based on the current value.
The caveat here is that I needed a 3-second interval between each API call to avoid surpassing the allowable limit of API calls per second.
In my attempt to resolve this issue, I created the following function to fetch a list of properties stored in an array:
const getPropertiesInCity = (properties) => {
for(i = 0; i < properties.length; i++){
let property = properties[i]
setTimeout(() => {
getPropertyDetails(property.zpid)
}, 5000)
}
}
The outcome of running this function resulted in a series of errors followed by successful responses, as indicated below:
Error
Error
Error
...
Have the property
Have the property
Have the property
The errors were a direct result of exceeding the specified time frame for sending requests. The function would pause for 5 seconds before producing all the errors at once, followed by 3 positive responses.