[英]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.