Given I have the following configuration:
let config = {
"requests": [
{
"resource": "foo",
"interval": 1000
},
{
"resource": "bar",
"interval": 500
},
{
"resource": "baz",
"interval": 3000
},
{
"resource": "qux",
"interval": 500
},
{
"resource": "zot",
"interval": 500
},
],
// other configs...
}
I need to make a recursive setTimeout calls where I check what resources should be requested from a server at a given call and make the request to the server.
For example, considering the array above:
After 500ms, since it's the smallest interval, I have to make a request and pass array of ['bar', 'qux', 'zot']
. After another 500ms, and since it's already 1000ms, the array should be ['bar', 'qux', 'zot', 'foo']
. After another 500 it should be again ['bar', 'qux', 'zot']
. When reaches 3000 - ['bar', 'qux', 'zot', 'foo', 'baz']
, and so on...
The configuration itself is coming from a server when the app starts and it's a black box to me. Meaning I can't know exactly what intervals may be configured and how many of them are there. Here I made them increase by 500ms for convenience only (though I think I might make it a technical requirement to the back-end guys, lets assume I can't).
I'm not sure how to tackle this problem. I thought maybe I should store an array of required intervals and do something with that array. Perhaps store a current request as an object with timestamp and interval. Something like that:
const { requests } = config
let intervals = new Set()
for (let obj of requests) {
intervals.add(obj.interval)
}
intervals = Array.from(intervals).sort((a, b) => a - b) //[500, 1000, 3000]
let currentRequest
const makeRequest = resources => {
// send request to server with given resources array
// init the next request by calling initRequest again
}
const initRequest = () => {
const interval = 500 // just for example, the actual interval should be determind here
const resources = [] // Here I should determine what should be the requested resources
setTimeout(() => {
makeRequest(resources)
}, interval)
}
initRequest()
But I'm not sure about the logic here. How can this be done? Any ideas, please?