Josh
Josh

Reputation: 71

How to run IF JS logic based on a percentage chance?

I have a variable and I want the variable to affect the chance of a function being ran. For example:

var chance = 0.80;

function () {
 if(????) { <== I want this to only run 80% of the time, or whatever chance is set to
}
}    

The function is going to run every few seconds. As chance gets higher I want the probability of the function running to increase.

Upvotes: 2

Views: 811

Answers (1)

DripDrop
DripDrop

Reputation: 1002

Try this(I tried to leave your existing code alone):

...
if(Math.random() < chance){
//code goes here
}

The good thing about keeping the chance variable in place is it allows you to change the chance mid-execution.

Upvotes: 4

Related Questions