0

I have a code below that is doing animations on a random element between 1 and 6. But here it repeats one number x amounts of times.

How can I change this code to not repeat a random number?

x = 6;
$("#best_brands > .flow > img").each(function() {

    var timer = Math.floor(Math.random() * 300) + 600
    var number = 1 + Math.floor(Math.random() * x);
    fadeBrands(timer, number); 

});

function fadeBrands(timer, number) {

        $('#best_brands > .flow > img:lt("'+number+'")').animate({
            opacity: 1
        }, timer);  

}
Kim
  • 1,128
  • 6
  • 21
  • 41

2 Answers2

4

Please read Matt's answer to this question:

var grabBag = [1,2,3,4,5,6,7,8,9,10];

// randomize order of elements with a sort function that randomly returns -1/0/1
grabBag.sort(function(xx,yy){ return Math.floor(Math.random() * 3) - 1; })

function getNextRandom(){
    return grabBag.shift();
};

var originalLength = grabBag.length;
for(var i = 0; i < originalLength .length; i++){
    console.log(getNextRandom());
}

Also may consider reading this question: Unique Random Number Generator Javascript

Community
  • 1
  • 1
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
0

There is an alternative way of doing the same: every time you get a random number you can store it in usedNumbers array and check if the next random number is already present usedNumbers array every time.

Germann Arlington
  • 3,315
  • 2
  • 17
  • 19