Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call random function Javascript, but not twice the same function

I use a function that randomly selects another function, which works. But sometimes it runs the same function twice or even more often in a row.

Is there a way to prevend this?

My current code:

window.setInterval(function(){
        var arr = [func1, func2, func3],
        rand = Math.floor(Math.random() * arr.length),
        randomFunction = arr[rand];
        randomFunction();
}, 5000);

Pretty simple so far. But how do I prevent func1 (for example) to run twice in a row

like image 938
TheLD Avatar asked Nov 20 '25 00:11

TheLD


1 Answers

You can simply store the index of the last function called and the next time, get a random number which is not the last seen index, like this

var lastIndex, arr = [func1, func2, func3];

window.setInterval(function() {
    var rand;
    while ((rand = Math.floor(Math.random() * arr.length)) === lastIndex) ;
    arr[(lastIndex = rand)]();
}, 5000);

The while loop is the key here,

while ((rand = Math.floor(Math.random() * arr.length)) === lastIndex) ;

Note: The ; at the end is important, it is to say that the loop has no body.

It will generate a random number and assign it to rand and check if it is equal to lastIndex. If they are the same, the loop will be run again till lastIndex and rand are different.

Then assign the current rand value to the lastIndex variable, because we dont't want the same function to be called consecutively.

like image 106
thefourtheye Avatar answered Nov 22 '25 16:11

thefourtheye