I am using setInterval();
function to run a function every 5 sec, but i want to clear this interval if some condition satisfied.
function do_the_job(){
//some code
if(some_condition)
{
clearInterval(interval);
}else{
clearInterval(interval);
var interval = setInterval(do_the_job(),5000);
}
}
function clearInterval();
is not working here.
通过将其声明移至if
语句之外,使interval
成为全局变量或“更高范围的变量”,以便在清除时实际上将其置于范围内。
This is not a good time to use setInterval()
, try setTimeout()
instead
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.
Make the interval
a global variable, and it will work.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.