How to pause setTimeout and then continue it?

Viewed 69

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

}

How to pause setTimeout and then continue it? It should be like when it hovered on text - picture stops auto slider, when it mouseout - auto slider is working Here i tried to do it with it_paused = false/true. But nothing succeeded. What am i doing wrong?

2 Answers

In fact, setTimeout internally can't be paused, but we can work around, it by when pause clearing the old setTimeout and checking the difference in time, and setting it in a variable called remaining, then when we resume creating a new setTimeout with the remaining time.

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>

Related