Javascript 随机化 setInterval(如何在随机间隔后重写相同的随机数)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6962658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:59:06  来源:igfitidea点击:

Randomize setInterval ( How to rewrite same random after random interval)

javascriptjquery

提问by Roko C. Buljan

I'd like to know how to achieve: generate a random number after a random number of time. And reuse it.

我想知道如何实现:在随机数时间后生成一个随机数。并重复使用它。

function doSomething(){
     // ... do something.....
}

var rand = 300; // initial rand time

i = setinterval(function(){

     doSomething();
     rand = Math.round(Math.random()*(3000-500))+500; // generate new time (between 3sec and 500"s)

}, rand); 

And do it repeatedly.

并且反复做。

So far I was able to generate a random interval, but it last the same until the page was refreshed (generating than a different time- interval).

到目前为止,我能够生成一个随机间隔,但它一直持续到页面刷新(生成不同的时间间隔)。

Thanks

谢谢

回答by Akkuma

Here is a really clean and clear way to do it:

这是一个非常干净和清晰的方法:

http://jsfiddle.net/Akkuma/9GyyA/

http://jsfiddle.net/Akkuma/9GyyA/

function doSomething() {}

(function loop() {
    var rand = Math.round(Math.random() * (3000 - 500)) + 500;
    setTimeout(function() {
            doSomething();
            loop();  
    }, rand);
}());

EDIT:

编辑:

Explanation: loop only exists within the immediately invoked function context, so it can recursively call itself.

说明:循环只存在于被立即调用的函数上下文中,因此可以递归调用自身。

回答by BrokenGlass

Something like this should work - use setTimeout()instead so you can set a new random value each time:

像这样的东西应该有效 -setTimeout()改用这样你每次都可以设置一个新的随机值:

function doSomething() {
    alert("doing something");
}

function init() {
    var myFunction = function() {
        doSomething();
        var rand = Math.round(Math.random() * (3000 - 500)) + 500; // generate new time (between 3sec and 500"s)
        setTimeout(myFunction, rand);
    }
    myFunction();
}

$(function() {
    init();
});

Working jsFiddle here.

在这里工作 jsFiddle

回答by Nazin

Just setup interval each time you rand (and clear it first)

每次 rand 时只设置间隔(并先清除它)

function doSomething(){
     // ... do something.....
}

var i;
var rand = 300;

function randomize() {
    doSomething();
    rand = Math.round(Math.random()*(3000-500))+500; 
    clearInterval(i);
    i = setInterval('randomize();', rand);
}

i = setInterval('randomize();', rand);

or try using setTimeout (and setting again after randing)

或尝试使用 setTimeout (并在 randing 后再次设置)

回答by Alexander Mills

Just throwing my hat in the ring

只是把我的帽子扔进戒指

    var keepLooping = true;
    (function ontimeout(){
        if(keepLooping){
            doTheAction();
            setTimeout(ontimeout, Math.random() * 100);
        }
    })();

depends if you want to put doTheAction()inside the setTimeoutcallback or not. I think it's fine to put it before/outside. If you want the initial delay, then put it inside, if not, put it outside for simplicity.

如果你想把取决于doTheAction()内部setTimeout回调与否。我认为把它放在前面/外面很好。如果你想要初始延迟,那么把它放在里面,如果没有,为了简单起见,把它放在外面。

回答by jabacchetta

Here's a reusable version that can be cleared. Open-sourced as an NPM packagewith IntelliSense enabled.

这是一个可以清除的可重用版本。作为启用 IntelliSense的 NPM 包开源。

Utility Function

实用功能

const setRandomInterval = (intervalFunction, minDelay, maxDelay) => {
  let timeout;

  const runInterval = () => {
    const timeoutFunction = () => {
      intervalFunction();
      runInterval();
    };

    const delay = Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;

    timeout = setTimeout(timeoutFunction, delay);
  };

  runInterval();

  return {
    clear() { clearTimeout(timeout) },
  };
};

Usage

用法

const interval = setRandomInterval(() => console.log('Hello World!'), 1000, 5000);

// // Clear when needed.
// interval.clear();