Home > Back-end >  How to pause setTimeout and then continue it?
How to pause setTimeout and then continue it?

Time:06-25

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?

CodePudding user response:

In this case, you may try using setInterval instead of setTimeout.

About setInterval:
https://www.w3schools.com/jsref/met_win_setinterval.asp

CodePudding user response:

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>

CodePudding user response:

Here's a sample code that I used for one of my projects. I believe that will help (I'm assuming you are familiar with '$')-

var TimeOutCall;
$(element).mouseout( function () {
    TimeOutCall = setTimeout("mytimeoutfunction()", 3000)
});

$(element).mouseover( function () {
  clearTimeout(TimeOutCall);
});
  • Related