Last Updated: February 25, 2016
·
195
· elfenars

Random without repeating last

So i wanted to randomly print out the items of an array whitout repeating the last thing printed in JavaScript. This came out:

lastIndex = 0; // Just the first time. Could be a random number too.

setInterval(function(){
  lastIndex = dnr(lastIndex, 10); // 10 being the max.
  console.log(lastIndex);
}, 1000); // Every 1 sec.

// Do not repeat. Never gives the same number twice.
function dnr(lastIndex, length){
  var randIndex = Math.floor((Math.random()*length));

  while (randIndex == lastIndex){
    var randIndex = Math.floor((Math.random()*length));
  }
  return randIndex;
}