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;
}Written by Feña Agar
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#