Помимо случайной задержки нужно еще ограничить количество одновременных запросов, примерно так:
function randomDelay(min = 250, max = 750) {
return new Promise((resolve) => {
const ms = Math.random() * (max - min) + min;
setTimeout(resolve, ms);
});
}
function downloadAll(urls, limit = 4) {
return new Promise((resolveAll, rejectAll) => {
const result = [];
const iter = urls.entries();
let fulfilled = 0;
const next = () => {
const { done, value } = iter.next();
if (done) {
if (fulfilled === urls.length) {
resolveAll(result);
return;
}
return;
}
const [index, url] = value;
const onFulfilled = (val) => {
result[index] = val;
fulfilled += 1;
next();
};
randomDelay()
.then(() => fetch(url))
.then(onFulfilled, rejectAll);
};
for (let i = 0, l = Math.min(limit, urls.length); i < l; i++) {
next();
}
});
}
const urls = Array.from(
{ length: 100 },
(_, i) => `https://jsonplaceholder.typicode.com/todos/${i + 1}`
);
(async () => {
const responses = await downloadAll(urls, 2);
const data = await Promise.all(responses.map((r) => r.json()));
console.log(data);
})();