'How to make timed requests to a server to avoid rate-limiting using Javascripts setTimeout?
I am trying to use setTimeout in a for loop so that my HTTP requests get sent once per second to avoid rate-limiting. However, it doesn't seem to be working. Could someone please help?
async function initiateSearchExperimental() {
const json = await getCollections();
for (let i = 0; i < json.result.data.length; i++) {
setTimeout(getData(json, i), 1000 * i)
}
}
function getData(json, i) {
fetch(`https://howrare.is${json.result.data[i].url}/?for_sale=on&sort_by=rank`).then(function(response) {
// The API call was successful!
return response.text();
}).then(function(html) {
// Convert the HTML string into a document object
var parser = new DOMParser();
var doc = parser.parseFromString(html, 'text/html');
var priceArray = getPriceArray(doc.querySelectorAll("div.featured_item"))
console.log(json.result.data[i].url, curateArrayTwo(priceArray, json.result.data[i]))
}).catch(function(err) {
// There was an error
console.warn('Something went wrong.', err);
});
}
Solution 1:[1]
No need for await and such
I suggest you DO use setTimeout, but do it in the success of the second fetch
let data;
let cnt = 0;
const getData() {
if (cnt >= data.length) return; // stop
fetch(`https://howrare.is${data[cnt].url}/?for_sale=on&sort_by=rank`)
.then(function(response) {
// The API call was successful!
return response.text();
}).then(function(html) {
// Convert the HTML string into a document object
var parser = new DOMParser();
var doc = parser.parseFromString(html, 'text/html');
var priceArray = getPriceArray(doc.querySelectorAll("div.featured_item"))
console.log(data[cnt].url, curateArrayTwo(priceArray, data[cnt]))
cnt++
setTimeout(getData, 1000)
}).catch(function(err) {
// There was an error
console.warn('Something went wrong.', err);
});
};
fetch(collectionurl)
.then(response => response.json())
.then(json => {
data = json.result.data;
getData()
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mplungjan |
