Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

clearInterval() function is not working in JavaScript

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading