简体   繁体   English

如何在JQuery中重复清除setInterval函数

[英]How to clear repeatedly set setInterval function in JQuery

I am using the below code to call a function recursively based on the condition. 我使用下面的代码根据条件递归调用函数。 But once the setInterval is set, It is not clear and again and again the setInterval is set. 但是一旦设置了setInterval,就不清楚了,并且一次又一次地设置了setInterval。 How to clear the repeatedly set setInterval function ? 如何清除重复设置的setInterval函数?

function testFunction(ttlcount){

        jQuery.ajax({url:URL,
           type: "POST",
           data: { 'action_sub':'action'},
           success:function(res){

                            if(res < 0){ 
                                 if(interval != 'undefined'){
                                   clearInterval(setInterval); //clearinterval
                                 }
                                interval = setInterval(function(){testFunction(ttlcount)},1000); 

                              } else {
                                 clearInterval(interval);//clearinterval
                 //Do something ...   
                             }


        },error:function(e){

        }});
    }

Try 尝试

setTimeout(callback function, timeout)

This will only run once, and if you need to run this single timer, then call it again. 这只会运行一次,如果你需要运行这个单一计时器,那么再次调用它。

if(interval != 'undefined'){
  clearInterval(testFunction); //clearinterval
}

This should actually be: 这应该是:

if(interval !== undefined){
  clearInterval(interval); //clearinterval
}

When you call setInterval, you get a reference back to the actual set interval. 当您调用setInterval时,您将获得一个返回实际设置间隔的引用。 That is the reference you need to pass to clearInterval to stop it, not the callback to be executed by setInterval. 这是您需要传递给clearInterval以停止它的引用,而不是由setInterval执行的回调。

在2019年,你可以使用我的jQuery / Zepto插件设置你想要的每个状态https://github.com/xpectmore/jQuery-Interval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM