Skip to content

Instantly share code, notes, and snippets.

@neutraltone
Last active January 13, 2016 23:57
Show Gist options
  • Save neutraltone/5540381 to your computer and use it in GitHub Desktop.
Save neutraltone/5540381 to your computer and use it in GitHub Desktop.
Randomly print out the items of an array without repeating the last thing printed in JavaScript. https://coderwall.com/p/m_jldw
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment