blogdoodlesgamessounds
blogdoodlesgamessounds
  1. Home
  2. blog
  3. Once Every N

Once Every N

A useful utility for randomization.

Jan 25, 2021
#JavaScript#randomization

Motivation

Randomization can be a useful tool in generative art.

Here is a useful utility that is true once every n times, on average.

Code

function onceEvery(n) {
return Math.floor(Math.random() * n) === 0;
}

and an example:

if (onceEvery(10)) {
console.log('This fires randomly with odds 1:10');
} else {
console.log('This fires randomly with odds 9:10');
}