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

Why the interval will become faster and faster if I keep setting new interval

I am doing a very simple timer with two buttons: stop and set.

Here is the code:

   <h1>0</h1>
   <button onclick = 'set()'>Set</button>
   <button onclick = 'stop()'>Stop</button>

     var click = false;
        let interval
    function set(){
        interval = setInterval(function(){
    document.querySelector('h1').textContent = parseFloat(document.querySelector('h1').textContent)+1
        },1000)
    }
    function stop(){
        window.clearInterval(interval)
    }

I found that if I keep pressing the set button which will set new interval, the speed of adding 1 to h1 will become faster and faster (which is much faster than 1000 ms).

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

I know I could gather the two buttons to one button, or make the set button become display: none or use other ways to prevent this situation.

But I just wonder why does this happens.

Could someone explain me a little bit about why this happens?

Thanks for any responds?

>Solution :

That’s because you are not clearing the previous interval (simply reassigning it) on your set function, so if you click on set three times, you are running three intervals.

The proper code should be:

function set(){
  clearInterval(interval);

  interval = setInterval(function(){
    document.querySelector('h1').textContent = parseFloat(document.querySelector('h1').textContent)+1
  }, 1000)
}
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