You can do this with two methods, first setTimeout
and second requestAnimationFrame
.
Here are the full examples of both.
Random interval with setTimeout
function randomInterval(callback, min, max) {
let timeout;
const randomNum = (max, min = 0) => Math.random() * (max - min) + min;
const stop = () => clearTimeout(timeout)
const tick = () => {
let time = randomNum(min, max);
stop();
timeout = setTimeout(() => {
tick();
callback && typeof callback === "function" && callback(stop);
}, time)
}
tick();
}
Random interval using requestAnimationFrame
function randomInterval(callback, min, max) {
const randomNum = (max, min = 0) => Math.random() * (max - min) + min;
let targetTime = randomNum(min, max);
let lastInvoke = performance.now();
const stop = () => targetTime = null
const tick = () => {
if (!targetTime) return;
if (performance.now() - lastInvoke > targetTime) {
lastInvoke = performance.now();
targetTime = randomNum(min, max);
callback && typeof callback === "function" && callback(stop);
}
requestAnimationFrame(tick)
}
tick();
}
and here is an example of how to call it
randomInterval((stop) => {
// do what you want...
if (stopCondition) {
stop();
}
}, 1000, 3000)