Reputation: 1290
I'm looking for random counting without duplicate numbers I found something like this without comment random
var randnums = [0,1,2,3,4,5,6];
setInterval(function() {
var m = Math.floor(Math.random()*randnums.length);
$('ul li:nth-of-type('+(randnums[m])+')').animate({
opacity:1
},400)
console.log(randnums[m])
}, 300);
EXAMPLE: CODEPEN
What I want to accomplish:
when u check console log you will see that random isn't working as I think suppose to. I think random should work for example 4,3,5,1,6,2 with interval 300 for each number. Now it is working like every 300 ms choose numer 1,2,2,4,5,0 etc so after 4 sec you couldnt see for example 1.
second think I want to create script which count elements .lenght of elements (li) then create array and pick random numbers without duplicate.
I was looking for help all over net for long time with no positive result.
Upvotes: 0
Views: 139
Reputation: 23396
Test this:
var randnums = [0, 1, 2, 3, 4, 5, 6],
delay = setInterval(function () {
var m = Math.floor(Math.random() * randnums.length);
console.log(randnums[m]);
randnums.splice(m,1);
if (!randnums.length) {
clearInterval(delay);
}
}, 300);
splice()
is a very important part of this script, it "throws away" a used number. I've also added a check, which stops the interval, when all numbers are used.
EDIT
You can create an array of length of X with a for
loop, for example:
var randnums = [], n, len = 12;
for (n = 0; n < len; n++) {
randnums.push(n);
}
Upvotes: 1
Reputation: 324620
An alternative to splicing, if you want to be able to reuse the array or loop the animation, try this:
var randnums = [0,1,2,3,4,5,6];
randnums.sort(function(a,b) {return Math.random()-0.5;}); // "shuffle" the array
setInterval(function() {
var n;
randnums.push(n = randnums.shift()); // cycle the first element to the back
// do something with n
},300);
Upvotes: 0