[SOLVED] How can I write a javascript that generates random numbers automatically every second?

Issue

God! I’m going nuts…🙆‍♂️

I want a javascript code whereby in an array of numbers for example (202,157), the numbers that generate or change randomly every second from a minimum of 100 to a maximum of 600 are only the last three (157 for instance), and every previously generated random numbers go below the newly generated random numbers.

For instance, if the first number generated is 202,157 the second will probably be 202,364 or 202,176 probably, but the first three numbers (202) don’t change.

Take this set for example

202,411

202,203

202,422

202,301

202,157

They are separated by a comma but only the last three numbers change randomly.

I’ve tried my possible best, but mehn, I don’t even know what I’m writing anymore. I’m going nuts.

var random = Math.random[min,max];

     function getRandomInt(min, max){
            document.getElementById("ballerii").innerHTML = random;
     } 
     
setInterval(random, 1000);

Please anyone that understands what I seek, can help me find please. If you know anyone that can help too, please refer him/her. Thank you.

Solution

You need to call Math.random() inside the function to get a new random number.

Math.random() doesn’t take arguments to specify a range. See Generating random whole numbers in JavaScript in a specific range? for how you can do that.

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function showRandomInt() {
  let newdiv = document.createElement("div");
  newdiv.innerText = "202," + getRandomInt(100, 600);
  document.getElementById("ballerii").insertAdjacentElement("afterbegin", newdiv);
}

setInterval(showRandomInt, 1000);
<div id="ballerii">
</div>

Answered By – Barmar

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.