Javascript 如何退出setInterval
如果条件正确,我需要退出运行间隔:Javascript 如何退出setInterval,javascript,setinterval,Javascript,Setinterval,如果条件正确,我需要退出运行间隔: var refreshId = setInterval(function() { var properID = CheckReload(); if (properID > 0) { <--- exit from the loop---> } }, 10000); var refreshId=setInterval(函数(){ var properID=Check
var refreshId = setInterval(function() {
var properID = CheckReload();
if (properID > 0) {
<--- exit from the loop--->
}
}, 10000);
var refreshId=setInterval(函数(){
var properID=CheckReload();
如果(properID>0){
}
}, 10000);
使用:
为ES6更新
您可以限定变量的范围以避免污染命名空间:
const CheckReload=(()=>{
让计数器=-5;
return()=>{
计数器++;
返回计数器;
};
})();
{
常数refreshId=setInterval(
() => {
const properID=CheckReload();
console.log(properID);
如果(properID>0){
clearInterval(刷新ID);
}
},
100
);
}
将设置间隔的值传递给
简单例子
const interval=setInterval(()=>{
间隔时间;
}, 1000)
倒计时示例
计时器每秒递减一次,直到达到0
让secondsToCountDown=2
常量间隔=设置间隔(()=>{
//只是为了展示
document.querySelector('.timer')。innerHTML=secondsToCountDown
如果(秒倒计时===0){
clearInterval(interval);//时间到了
}
第二种方法--;
}, 1000);代码>
只需调用clearInterval(intervalName)
,例如:var helloEverySecond=setInterval(function(){console.log(“hello”);1000)代码>可通过clearInterval(helloEverySecond)停止代码>这是Javascript的一个全新级别。在自己的声明中引用变量。refreshId周围的大括号扮演什么角色?谢谢
var refreshId = setInterval(function() {
var properID = CheckReload();
if (properID > 0) {
clearInterval(refreshId);
}
}, 10000);