(function() {
"use strict";
// edit the following values range
const range = [1, 150]; // [from, to] inclusive
// if you want to exclude any numbers add them below
const numbersToExclude = [];
/////////////////////////////////////////////////////////////////////////////////
const button = document.getElementById("pick");
const luckyPerson = document.getElementById("lucky_person");
let timer = null;
const [from, to] = range;
button.addEventListener("click", function() {
if (!timer) {
// Start drawing random numbers
timer = window.setInterval((el) => {
el.innerHTML = Math.floor(Math.random() * (to - from) + from);
}, 50, luckyPerson);
button.innerHTML = "Pick winner!";
document.body.className = "";
} else {
clearInterval(timer);
timer = null;
button.innerHTML = "Draw";
document.body.className = "result";
luckyPerson.innerHTML = drawWinner(range, numbersToExclude)
}
});
/**
* Pick a random number between startNo and endNo included.
* Note: this function handles ranges from 0 up to 65535
*
* @param {(number, number)} range - a range of numbers (0 - 65535) to pick inclusive
* @param {number[]} numbersToExclude - an optional array of numbers to exclude from
* the above range
* @returns number - the lucky number
*/
function drawWinner([from, to] = [0, 100], numbersToExclude = []) {
if (from >= to || from < 0 || to > 65535) {
throw new Error("range should be from 0 up to 65535 and 'from' smaller than 'to'");
}
let winner = self.crypto.getRandomValues(
to > 255 ?
new Uint16Array(1) :
new Uint8Array(1)
);
while (
winner[0] < from ||
winner[0] > to ||
numbersToExclude.includes(winner[0])
) {
winner = self.crypto.getRandomValues(winner);
}
return winner[0];
}
}());
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.