在递归函数中停止settimeout

13 javascript jquery settimeout

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

我有这个方法 来设置这个论坛的超时.它应该将标识符存储在全局变量中.我意外地发现,在我隐藏"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();
               }
});
Run Code Online (Sandbox Code Playgroud)

谢谢,理查德

Bri*_*ead 22

我认为大多数人都在理解为什么这不起作用,但我想我会为你提供更新的代码.它与您的几乎完全相同,只是它将超时分配给变量以便可以清除它.

此外,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();
   }
});
Run Code Online (Sandbox Code Playgroud)


yle*_*bre 7

我认为你误解了'setTimeout'和'clearTimeout'.

如果要设置要在以后取消的计时器,请执行以下操作:

foo = setTimeout(function, time);
Run Code Online (Sandbox Code Playgroud)

然后打电话

clearTimeout(foo);
Run Code Online (Sandbox Code Playgroud)

如果你想取消那个计时器.

希望这可以帮助!