如何暂停setTimeout调用?

8

可能是重复问题:
javascript:暂停setTimeout();

我正在使用jQuery为我的网站开发通知系统。 通知使用setTimeout函数自动淡出。

如何停止setTimeout调用的定时器?

例如,当鼠标悬停在通知上时,我希望暂停setTimeout调用的计时器,并在鼠标移出时继续倒计时...

我尝试了谷歌搜索“暂停setTimeout”,但没有找到相关结果。

目前,我正在使用clearTimeout清除setTimeout调用,并同时在鼠标移出时淡出通知,但拥有暂停效果会更好。

有什么想法吗?


3
当鼠标悬停在通知上时,重置计时器不是很合理吗?我的意思是,如果计时器在剩下1毫秒时暂停,那么用户在再次移开鼠标后将没有时间。 - Bob
我没有解释整个过程,但它会根据消息的长度增加时间。 - Pablo
3个回答

11

试试这个。

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

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

7

增加一个可暂停的PausableTimeout类并不难:

(可能不是有效的JS代码,但让它工作起来不应该太难):

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

当然,在其中添加一些错误检查是个好主意(不希望有可能取消暂停超时多次并最终得到数百个超时!),但我会让这成为你的工作:P


4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接