Javascript: Random Number Generator (Dynamic) -
i add random number generator site. idea have code outputs random number between min , max value (i.e. 200-400) updates in real time, without page refresh. came across this, doesn't need since number generated on click rather dynamically (without action on user's part). plus, if set range 400 , min value 230, snippet outputs numbers aren't within range (i.e. 580).
it better have numbers display not randomly (i.e. 340, 348, 367, 330, 332, 330, 345, 357 etc). isn't mandatory.
thank help!
randwithvariation()
takes min , max value maximum offset previous value , returns function can use.
function randwithvariation(min, max, variation) { var seed = (math.floor(math.random() * max) % (max - min)) + min; // attempts keep result within 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 number decrease seed += offset; if (seed < min) return max - seed; // attempts keep result within 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>
Comments
Post a Comment