javascript setinterval随机时间

时间:2016-01-07 13:47:22

标签: javascript

我有这个setinterval with function alert:

setInterval(function(){
    alert('oo');
}, 5000);

但是我想在每次间隔运行alert()时更改我的(5000)间隔 - 我想在5到10秒之间随机选择它。知道怎么做吗?

5 个答案:

答案 0 :(得分:5)

您应该使用setTimeout来设置应该执行该功能的间隔。



function myFunction() {
  var min = 5,
    max = 10;
  var rand = Math.floor(Math.random() * (max - min + 1) + min); //Generate Random number between 5 - 10
  alert('Wait for ' + rand + ' seconds');
  setTimeout(myFunction, rand * 1000);
}

myFunction()




答案 1 :(得分:2)

你可以这样做:

/media/sf_VboxShared/Data/csv/res20150201

答案 2 :(得分:0)

间隔一旦设定,就会被修复。

使用setTimeout并以递归方式调用该函数。

function myAlert() {
    setTimeout(myAlert, generate_random_time());
    alert('oo');
}

答案 3 :(得分:0)

此处大多数当前答案的唯一潜在问题是,初始函数调用没有随机延迟,只有随后的调用。

一种修改是将函数放在循环外部,然后在setTimeout内部调用它:

function doSomething() {
    console.log("Hello");
}

(function loop() {
    var rand = Math.round(Math.random() * 10);
    setTimeout(function() {
            doSomething();
            console.log("Delayed " + rand + " secs.");
            loop();  
    }, rand*1000);
}());

学习将ES6转换为箭头函数和模板文字的代码,就像这样:

function doSomething() {
    console.log("Hello");
}

(function loop() {
    let rand = Math.round(Math.random() * 10);
    setTimeout( () => {
            doSomething();
            console.log(`Delayed ${rand} secs`);
            loop();  
    }, rand*1000);
}());

改编自非常相似的线程:https://stackoverflow.com/questions/6962658/randomize-setinterval-how-to-rewrite-same-random-after-random-interval

答案 4 :(得分:0)

您可以使用两种方法来做到这一点,第一种是setTimeout,第二种是requestAnimationFrame

这是两者的完整示例。

随机间隔为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();
}

使用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();
}

这是如何调用它的示例

randomInterval((stop) => {
    // do what you want...

    if (stopCondition) {
        stop();
    }
}, 1000, 3000)
相关问题