如何在setInterval函数中生成第二个参数(持续时间)的随机持续时间值

How to generate random duration value of second argument ( duration) in setInterval function

本文关键字:持续时间 参数 随机 第二个 setInterval 函数      更新时间:2023-09-26

如何在setInterval函数中生成第二个参数(持续时间)的随机持续时间值。

 //such as

 var timerId = setInterval( timer_counter,getRandomInt(5,60),number,slatt);
var n = 10, // max value
    r = Math.floor(Math.random() * n) + 1; // random number (1-10)
setInterval(function(){
  timer_counter();
}, r * 1000); // to milliseconds

你正在寻找我相信Math.random()(加上Math.floor)。

注意:如果r(例如)为 3,它将在该间隔的生命周期内每 3 秒执行一次。如果要更改它,则需要使用setTimeout并更改每次调用的超时。所以要做到这一点:

function worker(){
  // the code that should be executed
}
function repeat(){
  var n = 10; // every 1-10 seconds
  setTimeout(function(){
    worker();
    repeat();
  }, (Math.floor(Math.random() * n) + 1) * 1000);
}();

并为您提供getRandomInt功能:

function getRandomInt(nMax, nMin){
  nMax = nMax || 10;
  nMin = nMin || 0;
  return Math.floor(Math.random() * (nMax - nMin + 1)) + nMin;
}