How to pause a setTimeout call?

20,213

Solution 1

Try this.

var myTimeOut;
$(someElement).mouseout( function () {
  myTimeOut = setTimeout("mytimeoutfunction()", 5000)
});

$(someElement).mouseover( function () {
  clearTimeout(myTimeOut);
});

Solution 2

It wouldn't be too hard to add a PausableTimeout class:

(Might not be valid JS, but it shouldn't be too hard to get it working):

    function PausableTimeout(func, millisec) {
        this.func = func;
        this.stTime = new Date().valueOf();
        this.timeout = setTimeout(func, millisec);
        this.timeLeft = millisec;
    }
    function PausableTimer_pause() {
        clearTimeout(self.timeout);
        var timeRan = new Date().valueOf()-this.stTime;
        this.timeLeft -= timeRan;
    }
    function PausableTimer_unpause() {
        this.timeout = setTimeout(this.func, this.timeLeft);
        this.stTime = new Date().valueOf();
    }
    PausableTimer.prototype.pause = PausableTimer_pause;
    PausableTimer.prototype.unpause = PausableTimer_unpause;

    //Usage:
    myTimer = new PausableTimer(function(){alert("It works!");}, 2000);
    myTimer.pause();
    myTimer.unpause();

Of course, it'd be a great idea to add some error checking in there (don't want it to be possible to unpause the timeout multiple times and end up with hundreds of timeouts!), but I'll let that be your job :P

Solution 3

Use clearTimeout() on mouseover event and use setTimeout() again on mouseout event.

http://www.w3schools.com/jsref/met_win_cleartimeout.asp

Share:
20,213

Related videos on Youtube

Pablo
Author by

Pablo

Hi, I am a humble self thought web developer always looking to learn new tech and skills. My biggest trait is not been able to code but been able to find simple solutions to otherwise complex problems.

Updated on May 26, 2020

Comments

  • Pablo
    Pablo almost 4 years

    Possible Duplicate:
    javascript: pause setTimeout();

    Im using jQuery and working on a notification system for my site. The notifications automatically fadeout using the setTimeout function.

    How can i stop the timer of the setTimeout call?

    For example i would like to pause the setTimeout call while the mouse is over the notification and continue the count down mouseout...

    I googled "pause setTimeout" with no luck.

    Im currently clearing the setTimeout call with clearTimeout and at same time fading out the notification on mouseout but it would be nice to have that pause effect.

    Any ideas?

    • Bob
      Bob about 14 years
      Doesn't it make sense, though, to reset the timer when the mouse is over the notification? I mean, if the timer is paused at 1 millisecond left then the user will have no time left after they mouse out again