https://jsfiddle.net/mhLaj3qy/1/
const changeTimeset = setTimeout(()=>{ if (is_paused) return; bgImage.style.backgroundImage = array[current] changeBackgroundImages(data, ++current % array.length) }, a) function chandgeBackgroundImageOnMouse() { samoyed.addEventListener("mouseover", ()=>{ bgImage.style.backgroundImage = house is_paused = true }) samoyed.addEventListener("mouseleave", ()=>{ is_paused = false }) } chandgeBackgroundImageOnMouse()
}
¿Cómo pausar setTimeout y luego continuarlo? Debería ser como cuando se cierne sobre el texto: la imagen detiene el control deslizante automático, cuando se aleja el control deslizante automático funciona. Aquí traté de hacerlo con it_paused = false/true. Pero nada tuvo éxito. ¿Qué estoy haciendo mal?
En este caso, puede intentar usar setInterval
en lugar de setTimeout
.
Acerca setInterval
:
https://www.w3schools.com/jsref/met_win_setinterval.asp
De hecho, setTimeout internamente no se puede pausar, pero podemos solucionarlo haciendo una pausa borrando el antiguo setTimeout y verificando la diferencia en el tiempo, y configurándolo en una variable llamada restante, luego cuando reanudemos la creación de un nuevo setTimeout con el tiempo restante.
class Timer { constructor(callback, delay) { this.remaining = delay this.callback = callback this.timerId = undefined; this.start = undefined; this.resume() } pause() { window.clearTimeout(this.timerId); this.timerId = null; this.remaining -= Date.now() - this.start; }; resume() { if (this.timerId) { return; } this.start = Date.now(); this.timerId = window.setTimeout(this.callback, this.remaining); }; } const pause = document.getElementById('pause'); const resume = document.getElementById('resume'); var timer = new Timer(function() { alert("Done!"); }, 5000); pause.addEventListener('click', () => { timer.pause(); }) resume.addEventListener('click', () => { timer.resume(); })
<button id="pause">Pause</button> <button id="resume">Resume</button>
Aquí hay un código de muestra que usé para uno de mis proyectos. Creo que eso ayudará (supongo que está familiarizado con '$')-
var TimeOutCall; $(element).mouseout( function () { TimeOutCall = setTimeout("mytimeoutfunction()", 3000) }); $(element).mouseover( function () { clearTimeout(TimeOutCall); });