Estoy haciendo un temporizador muy simple con dos botones: stop y set .
Aquí está el código:
<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) } Descubrí que si sigo presionando el botón de set que establecerá un nuevo intervalo, la velocidad de agregar 1 a h1 será cada vez más rápida (que es mucho más rápida que 1000 ms).
Sé que podría reunir los dos botones en un solo botón, o hacer que el botón de configuración se convierta en display: none o usar otras formas de evitar esta situación.
Pero me pregunto por qué sucede esto.
¿Alguien podría explicarme un poco por qué sucede esto?
Gracias por alguna respuesta?
Esto se debe a que no está borrando el intervalo anterior (simplemente reasignándolo) en su función de set , por lo que si hace clic en set tres veces, está ejecutando tres intervalos.
El código adecuado debe ser:
function set(){ clearInterval(interval); interval = setInterval(function(){ document.querySelector('h1').textContent = parseFloat(document.querySelector('h1').textContent)+1 }, 1000) }¿Otra manera, más fácil de usar?
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>de otra manera ? Más CONFIABLE , más elegante
Aprovechamiento de OOP: donde garantiza que se ejecuta un intervalo único por instancia
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>Otros ejemplos a continuación muestran el beneficio de usar este administrador:
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>