-1

i tried to add a simple random number generater upto 10. When code is excecuted its working fine and generating random numbers. after that i added a condition that when function generate 5 random number function should stop working, So I added clearInterval() function but there is no change in output.

var stop = setInterval(timer, 1000);
var t = 0;

function timer() {
   var count = 0;
   var X = document.getElementById("timer");
   var rnumber = Math.floor(Math.random() * 10);
   X.innerHTML = rnumber;
   
   count++;
   if (count == 5) {
     clearInterval(stop);
   }
}
<body>
<div id="timer">0</div>
</body>
David
  • 208,112
  • 36
  • 198
  • 279
Somraj
  • 23
  • 6
  • 4
    Move `var count = 0;` outside function. You are setting it to `0` every time. – Rayon Sep 07 '22 at 13:15
  • your count is always 0, it doesn't count up in your function. as rayon said, move the count outside of your function. Easiest way to find the issue would be a console.log before you increase your count. console.log(count). than you can see, it is always 0. – nosTa Sep 07 '22 at 13:16
  • `count` is set to zero whenever `timer` executes - see the first line of timer function. You could declare `count` outside the function like you do for `t`. – James Sep 07 '22 at 13:16

1 Answers1

1

You are resetting count to 0 every time. Here's how to do it

function timer() {
   if (!this.count) this.count = 0;
   var X = document.getElementById("timer");
   var rnumber = Math.floor(Math.random() * 10);
   X.innerHTML = rnumber;

   this.count++;
   if (this.count == 5) {
     clearInterval(stop);
   }
}

    var stop = setInterval(timer, 1000);
    
    function timer() {
       console.log("running");
       if (!this.count) this.count = 0;
       var X = document.getElementById("timer");
       var rnumber = Math.floor(Math.random() * 10);
       X.innerHTML = rnumber;
    
       this.count++;
       if (this.count == 5) {
         clearInterval(stop);
         console.log("stopped");
       }
    }
<div id="timer">a</div>
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • he is not resetting his count, he is always redeclaring it to 0 in his local variable. Maybe post a working example within a code tag containing some console.log, so you can directly see the output – nosTa Sep 07 '22 at 13:19