-3

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

 //such as



 var timerId = setInterval( timer_counter,getRandomInt(5,60),number,slatt);
4

1 回答 1

1
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 秒执行一次。如果要更改,则需要使用 asetTimeout并更改每次调用的超时时间。所以要做到这一点:

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;
}
于 2013-09-20T14:40:57.493 回答