Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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)
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

an other way ? More RELIABLE , More elegant

Leveraging OOP: where you guarantee a unique interval is running per instance

class IntervalManager {
   constructor(fn, delay){ this.fn= fn; this.delay= delay;}
   start() {this.stop(); this.id= setInterval(this.fn, this.delay);}
   stop() {if (this.id) clearInterval(this.id);}
}
//--- use it now

const counter = new IntervalManager(function(){
  let ui = document.querySelector('h1')
  ui.textContent = parseFloat(ui.textContent)+1
},1000);
<h1>0</h1>
<button onclick = 'counter.start()'>Set</button>
<button onclick = 'counter.stop()'>Stop</button>

Other examples below show the benefit of using this manager:

class IntervalManager {
   constructor(fn, i){ this.fn= fn; this.i= i;}
   start() {this.stop(); this.id= setInterval(this.fn, this.i);}
   stop() {if (this.id) clearInterval(this.id);}
}
//--- use it now
//-- example 1
const timer = new IntervalManager(() => {
  document.querySelector('#timer h4').textContent = new Date()
}, 1000)

//-- example 2
counterIncrem= 0
const counter = new IntervalManager(() => {
  counterIncrem++;
  document.querySelector('#counter h4').textContent = counterIncrem
}, 1000)
<section id="timer">
  <h1>Timer</h1>
  <h4>_</h4>
  <button onclick = 'timer.start()'>Start</button>
  <button onclick = 'timer.stop()'>Stop</button>
</section>


<section id="counter">
  <h1>counter</h1>
  <h4>_</h4>
  <button onclick = 'counter.start()'>Start</button>
  <button onclick = 'counter.stop()'>Stop</button>
</section>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda