I have this function:
var lazyLoadAjaxManager = (function() {
const MAX_PARALLEL_CALL = 5
var queue = [] //to store the URL
var activeCall = 0
function queueRequest(url) {
queue.push(url)
checkQueue()
}
function onPromiseCompleteOrFailure() {
activeCall--
checkQueue()
}
function checkQueue() {
if (queue.length && activeCall <= MAX_PARALLEL_CALL) {
let url = queue.shift()
if (!url) {
return
}
activeCall++
fetch(url)
.then(res => res.json())
.then(response => {
onPromiseCompleteOrFailure()
//TODO Write your custom logic here
console.log('Success:', JSON.stringify(response))
})
.catch(error => {
onPromiseCompleteOrFailure()
console.error('Error:', error)
})
}
}
return {
addRequest: queueRequest,
}
})()
//To use -> call addRequest(url). Usually for a large number of request, we will do it inside a loop. E.g
// for (const userId of userIds) {
// lazyLoadAjaxManager.addRequest(`https://example.com/user/${userId})
// }
lazyLoadAjaxManager.addRequest('https://example.com/request1')
lazyLoadAjaxManager.addRequest('https://example.com/request2')
lazyLoadAjaxManager.addRequest('https://example.com/request3')
lazyLoadAjaxManager.addRequest('https://example.com/request4')
And I need call max 5 times / seconds.
How to change this code to do it?