You can pass an optional time parameter to your window.requestAnimationFrame() callback (loop() in this case), and it will pass in the current amount of time (in milliseconds) since the first frame.
You can create a timer object to take advantage of that:
const Timer = (event, interval = 0) => {
let last = 0;
let total = 0;
return {
set interval(newInterval)
{
interval = newInterval;
},
update(time = 0) {
total += time - last;
if (total >= interval) {
event(this);
total = 0;
}
last = time;
}
};
};
Now you can do this:
const fooLogger = Timer((timer) => {
console.log('foo!');
timer.interval = 1000 + Math.floor(Math.random()) * 1000;1000);
}, 1500);
function loop(time) {
requestAnimationFrame(loop);
fooLogger.update(time);
}
requestAnimationFrame(loop);
And this should log "foo!" every 1 - 2 seconds. Update: The question specified a variable interval, that has been added.