I have this setinterval with function alert:
setInterval(function(){
alert('oo');
}, 5000);
But I would like to change my (5000) interval each time interval runs alert() - I'd like have it randomly selected between 5 - 10 seconds. How can I do it?
You should use setTimeout
to set interval after which the function should be executed.
function myFunction() {
var min = 5,
max = 10;
var rand = Math.floor(Math.random() * (max - min + 1) + min); //Generate Random number between 5 - 10
console.log('Wait for ' + rand + ' seconds');
setTimeout(myFunction, rand * 1000);
}
myFunction()
You can do it like this:
function myFunction() {
alert('oo');
setTimeout(myFunction, Math.random() * 5000)
}
myFunction()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With