简体   繁体   English

在 JavaScript 中使用随机时间的“setinterval”

[英]'setinterval' with random time in JavaScript

I have this setinterval with function alert:我有这个带有功能警报的setinterval:

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.但我想在每次运行 alert() 时更改我的 (5000) 间隔 - 我希望它在 5 - 10 秒之间随机选择。 How can I do it?我该怎么做?

You should use setTimeout to set interval after which the function should be executed.您应该使用setTimeout来设置执行函数的时间间隔。

 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 .您可以使用两种方法执行此操作,第一个是setTimeout ,第二个是requestAnimationFrame

Here are the full examples of both.这是两者的完整示例。

Random interval with setTimeout 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使用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)

Intervals, once set, are fixed.间隔一旦设置,就是固定的。

Use setTimeout and call the function recursively instead.使用setTimeout并递归调用该函数。

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

The only potential issue with most of the current answers here is that the initial function call does not have the random delay, only the subsequent calls.大多数当前答案的唯一潜在问题是初始函数调用没有随机延迟,只有后续调用。

A modification is to place the function outside the loop then call it inside the setTimeout:一种修改是将函数放在循环外,然后在 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);
}());

Learning ES6 converting to arrow functions and template literals the code looks like: Learning ES6 converting to arrow functions and template literals 代码如下所示:

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

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

Adapted from a very similar thread:https://stackoverflow.com/questions/6962658/randomize-setinterval-how-to-rewrite-same-random-after-random-interval改编自一个非常相似的线程:https://stackoverflow.com/questions/6962658/randomize-setinterval-how-to-rewrite-same-random-after-random-interval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM