rrrfusco rrrfusco - 1 month ago 11
Javascript Question

Vary SetInterval time

I'm trying to vary the time of the setInterval function, by selecting a different value of an array.

Why does the console log output return one index repeated, or nothing at all?

$("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;
}

Answer

It happens because you call randTimeout() only once. It is not being calculated every time. Your code is similar to:

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

If you want your interval to be executed at random intervals from the given array, you can utilize setTimeout:

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();

Comments