Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

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?

like image 608
Yusuf Avatar asked Nov 15 '25 10:11

Yusuf


2 Answers

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)
}
like image 117
Yuan-Hao Chiang Avatar answered Nov 18 '25 04:11

Yuan-Hao Chiang


an other way, more user friendly ?

const h1_element = document.querySelector('h1')
    , btSet      = document.querySelector('#bt-set')
    , btStop     = document.querySelector('#bt-stop')
    ;
var interval = 0
  , counter  = 0
  ;
btSet.onclick =()=>
  {
  btSet.disabled = true
  btStop.disabled = false
  interval = setInterval( ()=> { h1_element.textContent = ++counter }, 1000 )
  }
btStop.onclick =()=>
  {
  clearInterval(interval)
  btSet.disabled  = false
  btStop.disabled = true
  }
<h1>0</h1>
<button id="bt-set">Set</button>
<button id="bt-stop" disabled>Stop</button>
like image 38
Mister Jojo Avatar answered Nov 18 '25 06:11

Mister Jojo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!