Vary SetInterval时间

时间:2016-10-12 02:50:34

标签: javascript jquery

我试图通过选择不同的数组值来改变setInterval函数的时间。

为什么控制台日志输出会重复返回一个索引,或者什么都没有?

$("input.btn1").click(function() {
    var i = 0;
    //var timeOut = 1000;

    var timer = setInterval(function() {

/*  
    var timeArr = [
        1000,2000,3000
    ];
    var randInt = getRandomInt(0, 2);
    var timeOut = timeArr[randInt]; 
*/      


    if( i < btn2.length) {
             console.log("current timeout: " +timeOut);
         } else {
             clearInterval(timer);
            }
            i = i + 1;
        }, randTimeout());

}); 


function randTimeout() {
    var timeArr = [
        1000,2000,3000
    ];
    var randInt = getRandomInt(0, 2);
    var timeOut = timeArr[randInt]; 

    return timeOut;
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

1 个答案:

答案 0 :(得分:2)

之所以发生这种情况是因为您只拨打了一次randTimeout()。它不是每次都计算。您的代码类似于:

var timeout = randTimeout();
setInterval(function() {
  // ...
}, timeout);

如果您希望在给定数组中以随机间隔执行间隔,则可以使用setTimeout

&#13;
&#13;
var timer, prevDate = new Date(), hitsLeft = 10;

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randTimeout() {
  var timeArr = [100, 200, 300, 400, 500, 600];
  var randInt = getRandomInt(0, timeArr.length);
  var timeOut = timeArr[randInt];

  return timeOut;
}

function tick() {
  if (hitsLeft === 0) {
    console.log("Complete.");
    timer = null;
    return;
  }
  
  // Do whatever you need here. I just measure the passed time for demo
  var currDate = new Date();
  console.log("Passed time: " + (currDate - prevDate) + " ms (" + hitsLeft + " hits left)");
  prevDate = currDate; 

  // Here, you call tick() again, with random timeout
  hitsLeft--;
  timer = setTimeout(tick, randTimeout());
}

tick();
&#13;
&#13;
&#13;