Home > OS >  How to randomize the number before stopping at the lucky number. (Javascript)
How to randomize the number before stopping at the lucky number. (Javascript)

Time:03-01

I have a button that generates a random number (from 1-100) after a click. I have to make it:

  • Loop through random numbers with an interval of 100ms.
  • Loop stops after 10 numbers.
  • Disable the button when numbers are looping.
  • Enable the button when looping stops.

Not sure if I have done the code correctly, I am able to let numbers loop after click but unable to make it stop after 10 numbers. I am also unable to diable when looping and enable the button when looping stops. Appreciate your kind help. Thanks!

Here's my code:

btn.onclick= function (){  
var random = Math.floor(Math.random()*100 1);
var interval = setInterval(function(){ 
    random = Math.floor(Math.random()*100 1);
    document.getElementById("lucky").innerHTML = "Your Lucky Number is: "   random;},100);};

CodePudding user response:

  • Loop through random numbers with an interval of 100ms.
  • Loop stops after 10 numbers. clearInterval(interval);
  • Disable the button when numbers are looping. btn.disabled = true;
  • Enable the button when looping stops. btn.disabled = false;

var btn = document.getElementById('randomize');

btn.addEventListener('click', function () { 
  btn.disabled = true;
  var cpt = 0;
  var interval = setInterval(function() {
      cpt  ;
      var random = Math.floor(Math.random()*100 1);
      document.getElementById("lucky").innerHTML = "Your Lucky Number is: "   random;
      if (cpt === 10) {
        btn.disabled = false;
        clearInterval(interval);
      }
   },100);
});
<button id="randomize">click me</button>
<div id="lucky"></div>

  • Related