Javascript-停止重复函数

Javascript-停止重复函数,javascript,jquery,Javascript,Jquery,可能重复: 我有一个在页面加载时被调用的函数,它启动了一个重复函数: setTimeout(function () { repeat(); }, 8000) setTimeout(function () { repeat(); }, 8000) 这个函数每8秒调用一次repeat(),在这个函数中我有一点ajax,它可以更新页面上的计数器。单击计数器会为用户提供一个包含大量消息的下拉菜单。计数器值等于用户拥有的消息数。有点像F

可能重复:

我有一个在页面加载时被调用的函数,它启动了一个重复函数:

        setTimeout(function () {
            repeat();
        }, 8000)
setTimeout(function () {
    repeat();
}, 8000)
这个函数每8秒调用一次
repeat()
,在这个函数中我有一点ajax,它可以更新页面上的计数器。单击计数器会为用户提供一个包含大量消息的下拉菜单。计数器值等于用户拥有的消息数。有点像Facebook通知

单击下拉菜单时,Im使用jQuery隐藏并显示它:

  $('#messages').click(function () {
        $('#messagesDropDown').slideDown();
    })
    .mouseleave(function () {
        $('#messagesDropDown').slideUp();
    });
#messagesDropDown
可见时,我想停止
repeat()
功能,以防止在我查看当前邮件时更新邮件列表

在.mouseleave上,我想再次启动
repeat()
函数

任何人都知道如何在
中“停止”重复函数。单击
函数并在
上再次启动它。mouseleave

返回超时ID。您可以存储该值,然后在需要时使用停止超时

var timeout;
$('#messages').click(function () {
        $('#messagesDropDown').slideDown(function () {
            clearTimeout(timeout); // Cancel the timeout when the slideDown has completed.
        });
    })
    .mouseleave(function () {
        $('#messagesDropDown').slideUp();
        clearTimeout(timeout); // Cancel incase it's still running (you can also set `timeout` to undefined when you cancel with clearTimeout, and apply some logic here (`if (timeout == undefined)` so you can leave it running rather than restarting it)
        timeout = setTimeout(repeat, 8000); // Store the ID of the timeout
    });

setTimeout将设置重复事件;它只会触发一次(就像延迟事件一样)。请看(和)。

您说过此代码会启动一个重复函数:

        setTimeout(function () {
            repeat();
        }, 8000)
setTimeout(function () {
    repeat();
}, 8000)
由于
setTimeout
不会重复,因此我假设
repeat
函数本身会触发另一个
setTimeout
来在运行后再次调用自身(链式
setTimeout
调用)

如果是,您有两个选择:

  • 让一个控制变量告诉
    repeat
    是否工作。一个简单的布尔值就可以了。如果希望
    repeat
    跳过其工作,并让
    repeat
    检查它,请设置布尔值。这是一个非常简单的答案

  • 具有重复执行的控制功能,如:

    var repeatHandle = 0;
    function startRepeat() {
        if (!repeatHandle) {
            repeatHandle = setTimeout(repeatTick, 8000);
        }
    }
    function repeatTick() {
        repeatHandle = 0;
        repeat();
    }
    function stopRepeat() {
        if (repeatHandle) {
            clearTimeout(repeatHandle);
            repeatHandle = 0;
        }
    }
    
    …然后用它们来控制重复。确保修改
    repeat
    以调用
    startRepeat
    来安排下一次调用,而不是直接调用
    setTimeout

  • 看这里:setInterval()重复而不是setTimeout()