【问题标题】:Javascript: clearTimeout seems to only suspend, not reset or clear?Javascript:clearTimeout 似乎只暂停,不重置或清除?
【发布时间】:2010-09-29 00:09:32
【问题描述】:

我对 JS 非常陌生,正在尝试修改基于 JavascriptKit jQuery 的 megamenu 系统,以延迟显示菜单,直到鼠标悬停在锚点对象上指定的时间。

我现在面临的问题是,似乎在 mouseout 上调用的 clearTimeout 只是暂停了 setTimeout,而不是取消、清除、重置它。

此时我只是在 setTimeout 调用后显示一个警报。目前我将超时间隔设置为 2000 进行测试。

例如,由于我现在将其设置为 2 秒延迟,如果我在 1/2 秒内将鼠标悬停在对象上 4 次,那么当我将鼠标悬停在对象上 5 次时,我的测试警报框会立即出现。

我认为 clearTimeout 应该完全破坏定时事件。为什么它似乎只是暂停倒计时?

teststuff:function(){
    if(jkmegamenu.toggletest==1)
     {
         jkmegamenu.executetimedcommand()
         jkmegamenu.toggletest=0
     }
    else
     {
         //jkmegamenu.executetimedcommandcancel()
         clearTimeout(jkmegamenu.teststuff);
     }
    },

    executetimedcommand:function(){
        if(jkmegamenu.toggletest==1)
        {
            alert('abcde')
        }
    },

    canceltimedcommand:function(){
    clearTimeout(jkmegamenu.teststuff);
},

【问题讨论】:

  • 这是我在这里的第一篇文章。已找到代码按钮。下次还会用。
  • 如果它解决了您的问题,请不要忘记接受答案(咳嗽我的咳嗽):D

标签: javascript jquery


【解决方案1】:

clearTimeout 将计时器 id 作为参数,而不是函数引用。

例如,如果您为jkmegamenu.teststuff 设置超时,您可以这样做

// set the delayed call
var timerID = setTimeout(jkmegamenu.teststuff, 2000);

// cancel it
clearTimeout(timerID);
timerID = 0;

【讨论】:

    【解决方案2】:

    您将“teststuff”定义为一个函数,然后将其传递给clearTimeout()。如果变量从setTimeout() 返回,则传递给clearTimeout() 的内容。如果您将setTimeout() 的返回值分配给“teststuff”,然后重新定义它,您将无法将原始值传递给clearTimeout()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 2012-05-10
      • 1970-01-01
      相关资源
      最近更新 更多