So, I have a Button that could activate function one, function two or function three. But I want that there is a 60% chance that function one gets called from the button and a 20% chance for function two and three. Thanks for Help!

The code =

function one(){alert('one');}
function two(){alert('two');}
function three(){alert('three');}
<button id="mybutton"></button>

2 Answers

3
Aplet123 On Best Solutions

Consider the following code:

function activateRandom () {
    var random = Math.random(); // get a random number from 0 to 1
    if (random < 0.6) { // 60% chance to get below 0.6
        one();
    } else if (random < 0.8) { // 20% chance to go between 0.6 and 0.8
        two();
    } else { // 20% chance remaining
        three();
    }
}
1
Community On

With the button, do this.

<button type = "button">' put name of button here' </button>

for random percentage, do this.

var rand = Math.random(0, 100)

if(rand < 'put your random percentage here') {
'what function?'
}

Try using that for each function.