【问题标题】:Javascript - Stop a repeating function [duplicate]Javascript - 停止重复功能[重复]
【发布时间】:2011-05-26 07:19:59
【问题描述】:

可能重复:
How to pause a setTimeout call ?

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

        setTimeout(function () {
            repeat();
        }, 8000)

这个函数每 8 秒调用一次repeat(),在这个函数里面我有一些 ajax 来更新页面上的一个计数器。单击计数器会为用户提供一个包含许多消息的下拉菜单。计数器值等于用户拥有的消息数。有点像 Facebook 通知。

点击下拉菜单时我使用jQuery来隐藏和显示它:

  $('#messages').click(function () {
        $('#messagesDropDown').slideDown();
    })
    .mouseleave(function () {
        $('#messagesDropDown').slideUp();
    });

#messagesDropDown 可见时,我想停止repeat() 函数,以防止在查看当前消息时更新消息列表。

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

任何人都知道如何在.click 函数中“停止”重复函数并在.mouseleave 上重新启动它?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

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

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 将设置重复事件;它只会触发一次(如延迟事件)。请查看setInterval(和clearInterval)。

【讨论】:

    【解决方案2】:

    你说这段代码启动了一个重复函数:

    setTimeout(function () {
        repeat();
    }, 8000)
    

    由于setTimeout 不会重复,我假设repeat 函数本身会触发另一个setTimeout 在运行后再次调用自己(链接setTimeout 调用)。

    如果是这样,您有两种选择:

    1. 有一个控制变量告诉repeat是否做它的工作。一个简单的布尔值就可以了。当您希望repeat 跳过它的工作时设置布尔值,并让repeat 检查它。这是非常简单的答案。

    2. 拥有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

    【讨论】:

      猜你喜欢
      • 2022-12-08
      • 1970-01-01
      • 2019-11-27
      • 2015-04-24
      • 1970-01-01
      • 2021-10-20
      • 2011-05-04
      • 2021-07-18
      • 1970-01-01
      相关资源
      最近更新 更多