简体   繁体   English

重置具有不同值的JavaScript时间间隔?

[英]Reseting an JavaScript Interval with different value?

I have a small issue I can't seem to fix. 我有一个小问题,似乎无法解决。 I have a simple JavaScript code where I want to create a Interval that goes for a random amount of seconds, then after it finishes it should start over again and go for another random amount of seconds. 我有一个简单的JavaScript代码,我想在其中创建一个可以随机运行几秒的时间间隔,然后在完成后应该重新开始并再随机选择几秒钟。

My code looks like this 我的代码看起来像这样

 var selectedtimes = [3000, 5000, 15000, 10000] var randtimes = selectedtimes[Math.floor(Math.random() * selectedtimes.length)]; var sti = setInterval(function() { console.log("now") }, randtimes); function restartsti() { var restartinterval = setInterval(restartsti, selectedtimes[Math.floor(Math.random() * selectedtimes.length)]); } 

I tried to create a second function that would restart the interval but at the moment the interval takes only one random number and only uses that specific number as the duration. 我尝试创建第二个函数,该函数将重新启动间隔,但此刻间隔仅获取一个随机数,并且仅使用该特定数作为持续时间。

To simplify my Node.js console should show "now" every randtimes seconds 为了简化我的Node.js控制台,每隔randtimes秒应显示“ now”

Any solution to this? 有什么解决办法吗?

I'm grateful for any help 我很感谢你的帮助

setInterval is appropriate to use when the delay is intended to be consistent. 如果希望延迟一致,则可以使用setInterval

Since your delay is meant to be different each time, it's probably better to use setTimeout here: 由于每次的延迟都会有所不同,因此最好在此处使用setTimeout

 var times = [3000, 5000, 10000, 15000]; function start() { console.log("now"); var randTime = times[Math.floor(Math.random() * times.length)]; setTimeout(start, randTime); } start(); 

As Luke said, it's probably better to use setTimeout. 如Luke所说,最好使用setTimeout。

But if you want to keep using setInterval, you could stop the old one with clearInterval (providing the intervalID returned by the setInterval function) and start a new one : 但是,如果您想继续使用setInterval,可以使用clearInterval停止旧的(提供setInterval函数返回的intervalID)并开始一个新的:

var selectedtimes = [3000, 5000, 15000, 10000]

var randtimes = selectedtimes[Math.floor(Math.random() * selectedtimes.length)];


var sti = setInterval(function () {
    console.log("now")
    }, randtimes);

function restartsti() {
    clearInterval(sti);

    sti = setInterval(function() {
        console.log("now");
        restartsti()
    }, selectedtimes[Math.floor(Math.random() * selectedtimes.length)]);
}

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

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