简体   繁体   English

如何在JavaScript中清除递归调用中的间隔

[英]How to clear interval in recursive call in javascript

I am using setInterval(); 我正在使用setInterval(); function to run a function every 5 sec, but i want to clear this interval if some condition satisfied. 函数每5秒运行一次函数,但是如果某些条件满足,我想清除此间隔。

function do_the_job(){ 
 //some code
 if(some_condition)
  {
     clearInterval(interval);
  }else{
      clearInterval(interval);
      var interval = setInterval(do_the_job(),5000);
      }
 }

function clearInterval(); 函数clearInterval(); is not working here. 在这里不工作。

通过将其声明移至if语句之外,使interval成为全局变量或“更高范围的变量”,以便在清除时实际上将其置于范围内。

This is not a good time to use setInterval() , try setTimeout() instead 这不是使用setInterval()的好时机,而是尝试setTimeout()

function do_the_job(){ 
 //some code
 if(some_condition)
  {
     // job done
  }else{
      setTimeout(do_the_job,5000);
      }
 }

In your code the var interval =... is local, not visible outside the scope of the function call, and thus will not work in a recursive function. 在您的代码中, var interval =...是局部的,在函数调用范围之外不可见,因此在递归函数中不起作用。

Make the interval a global variable, and it will work. interval设为全局变量,它将起作用。

solution

var interval;
function do_the_job(){ 
 //some code
 if(some_condition)
  {
     clearInterval(interval);
  }else{
      clearInterval(interval);
      interval = setInterval(do_the_job(),5000);
      }
 }
 var interval = setInterval(do_the_job(),5000);

不应有假肢

 var interval = setInterval(do_the_job,5000);

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

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