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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With