在递归函数中停止settimeout [英] stop settimeout in recursive function

查看:638
本文介绍了在递归函数中停止settimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

my problem is that I can not stop a timer.

我有此方法从此论坛设置超时。
它应该将标识符存储在全局变量中。
偶然地,我发现它在我隐藏mydiv之后仍在运行。

I had this method to set a timeout from this forum. It supposed to store the identifyer in the global variable. By accident, I found out that it is still running after I hide "mydiv".

我现在还需要知道,如果递归函数创建了多个实例或只有一个超时。因为首先我认为它每次都会覆盖var mytimer。
现在我不太确定。

I also need to know now, if the recursive function creates multiple instances or just one for the timeouts. Because first I thought that it overwrites "var mytimer" everytime. Now I am not so sure.

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

What would be a solid way to stop the timer??

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();
               }
});

谢谢,Richard

thanks, Richard

推荐答案

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

I think that most people are getting at the reason why this isn't working, but I thought I would provide you with updated code. It is pretty much the same as yours, except that it assigns the timeout to a variable so that it can be cleared.

此外,setTimeout中的匿名函数很棒,如果要运行逻辑内联,更改函数内的'this'值,或将参数传递给函数。如果你只想调用一个函数,只需将函数名称作为第一个参数传递即可。

Also, the anonymous function in a setTimeout is great, if you want to run logic inline, change the value of 'this' inside the function, or pass parameters into a function. If you just want to call a function, it is sufficient to pass the name of the function as the first parameter.

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();
   }
});

这篇关于在递归函数中停止settimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆