Home > Net >  clearInterval() function is not working in JavaScript
clearInterval() function is not working in JavaScript

Time:09-08

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>

CodePudding user response:

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>

  • Related