javascript - 在递归函数中停止settimeout

标签 javascript jquery settimeout

我的问题是我无法停止计时器。

我有 this method从这个论坛设置超时。 它应该将标识符存储在全局变量中。 无意间,我发现隐藏“mydiv”后它还在运行。

我现在还需要知道,递归函数是创建多个实例还是只创建一个超时。因为起初我认为它每次都会覆盖“var mytimer”。 现在我不太确定。

停止计时器的可靠方法是什么?

var updatetimer= function () {
//do stuff
        setTimeout(function (){updatetimer();}, 10000);

}//end function


//this should start and stop the timer
$("#mybutton").click(function(e) { 
         e.preventDefault();
         if($('#mydiv').is(':visible')){
                   $('#mydiv').fadeOut('normal');
             clearTimeout(updatetimer);

        }else{
                   $('#mydiv').fadeIn('normal');
                   updatetimer();
               }
});

谢谢,理查德

最佳答案

我认为大多数人都明白这不起作用的原因,但我想我会为您提供更新的代码。它与您的几乎相同,只是它将超时分配给一个变量以便清除它。

此外,setTimeout 中的匿名函数也很棒,如果您想内联运行逻辑,请更改函数内部“this”的值,或将参数传递给函数。如果你只是想调用一个函数,将函数名作为第一个参数传递就足够了。

var timer = null; 

var updatetimer = function () {
    //do stuff

    // By the way, can just pass in the function name instead of an anonymous
    // function unless if you want to pass parameters or change the value of 'this'
    timer = setTimeout(updatetimer, 10000);
};

//this should start and stop the timer
$("#mybutton").click(function(e) { 
     e.preventDefault();
     if($('#mydiv').is(':visible')){
        $('#mydiv').fadeOut('normal');
        clearTimeout(timer);  // Since the timeout is assigned to a variable, we can successfully clear it now

    } else{
        $('#mydiv').fadeIn('normal');
        updatetimer();
   }
});

关于javascript - 在递归函数中停止settimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/995426/

相关文章:

javascript - 如何不断用新数据刷新图表?

javascript - Google map 标记的文本标签

javascript - 将数据传递给匿名 Javascript 函数

javascript - qTip2 中的 Ajax 表单

javascript - 如果 $(element).text() 在字符串中

node.js - 如何在 node.js 中清除超时

javascript - 将多个数组与javascript合并

Javascript 预加载图像以更改 css 背景图像

jquery - Firefox 24 不适本地将 css 应用于动态内容

asp.net - 使用 JQuery/ASP.NET 进行简单 ajax 聊天时出现堆栈溢出错误