簡體   English   中英

在 JavaScript 中使用隨機時間的“setinterval”

[英]'setinterval' with random time in JavaScript

我有這個帶有功能警報的setinterval:

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

但我想在每次運行 alert() 時更改我的 (5000) 間隔 - 我希望它在 5 - 10 秒之間隨機選擇。 我該怎么做?

您應該使用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()

你可以這樣做:

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

您可以使用兩種方法執行此操作,第一個是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)

間隔一旦設置,就是固定的。

使用setTimeout並遞歸調用該函數。

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

大多數當前答案的唯一潛在問題是初始函數調用沒有隨機延遲,只有后續調用。

一種修改是將函數放在循環外,然后在 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 代碼如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM