Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript setinterval with random time

Tags:

javascript

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?

like image 990
peter Avatar asked Jan 07 '16 13:01

peter


3 Answers

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()
like image 130
Satpal Avatar answered Nov 10 '22 08:11

Satpal


You can do it like this:

function myFunction() {
  alert('oo');
  setTimeout(myFunction, Math.random() * 5000)
}

myFunction()
like image 29
CoderPi Avatar answered Nov 10 '22 08:11

CoderPi


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)
like image 43
Behnam Azimi Avatar answered Nov 10 '22 07:11

Behnam Azimi