Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda