Reputation: 77
I would like to add a random number generator to my site. The idea is to have a code that outputs a random number between a min and max value (i.e. 200-400) that updates in real time, without any page refresh. I came across this, but it doesn't really do I need to since the number is generated on click rather than dynamically (without any action on the user's part). Plus, if I set the range to 400 and min value to 230, the snippet outputs numbers that aren't even within this range (i.e. 580).
It would be even better to have the numbers display not so randomly (i.e. 340, then 348, then 367, then 330, 332, 330, 345, 357 etc). But it isn't mandatory.
Thank you for the help!
Upvotes: 0
Views: 2558
Reputation: 2642
randWithVariation()
takes a min and max value as well as a maximum offset to its previous value and returns a function you can use.
function randWithVariation(min, max, variation) {
var seed = (Math.floor(Math.random() * max) % (max - min)) + min; // attempts to keep the result within the bounds
var min = min, max = max, variation = variation;
var r = function() {
var offset = Math.floor(Math.random() * variation);
if (Math.random() < 0.5) offset *= -1; // chance that number will decrease
seed += offset;
if (seed < min) return max - seed; // also attempts to keep the result within the bounds
if (seed > max) return min + (seed - max);
else return seed;
}
return r;
}
var rand = randWithVariation(200, 400, 10);
document.getElementById('rnd').innerHTML = rand();
setInterval(() => {
document.getElementById('rnd').innerHTML = rand();
}, 500);
<span id="rnd"></span>
Upvotes: 2
Reputation: 967
This can be an option: http://www.w3schools.com/code/tryit.asp?filename=FBVP9Q02RZFB
or
<!DOCTYPE html>
<html>
<body>
<p>Lots of random numbers</p>
<p id="demo"></p>
<script>
//returns a random number beetween min and max
function randMinMax(min , max) {
return min + Math.floor((Math.random() * max));
}
function updateEveryXms(min , max, ms) {
//start allredy with a random number instad of waiting ms
document.getElementById("demo").innerHTML = randMinMax(min,max);
//do it for ever and ever
setInterval(
function(){
document.getElementById("demo").innerHTML = randMinMax(min,max);
}, ms);
}
updateEveryXms(10 , 150, 1000);
</script>
</body>
</html>
Upvotes: 1