简体   繁体   English

setInterval 不能连续工作并在第一次迭代后停止

[英]setInterval doesn’t work continuously and stops after first iteration

The start is 01:59 .开始时间是01:59 When I refresh the page, it becomes 01:58 and stops on that.当我刷新页面时,它变为01:58并停止。 It should become 01:59 , then 01:58 , then 01:57 etc.它应该变成01:59 ,然后是01:58 ,然后是01:57等等。

 function timer() { let time = 119, minutes = Math.floor(time / 60), seconds = time % 60; if (minutes < 10) { minutes = `0${minutes}`; } else if (seconds < 10) { seconds = `0${seconds}`; } if (seconds > 0) { seconds = seconds - 1; } else { clearInterval(SI); } document.getElementById('div').innerHTML = `${minutes}:${seconds}`; } let SI = setInterval(() => { timer(); }, 1000);
 <div id="div"></div>

You are restting the time variable on each time() iteration.您在每次time()迭代时都在休息time变量。 Move the initialization outside the function.将初始化移到 function 之外。

Also, you've forgot to remove 1 second from the time variable after the function call time-- ;此外,您忘记在time--调用时间之后从time变量中删除 1 秒 - ;

 function timer() { let minutes = Math.floor(time / 60), seconds = time % 60; if (minutes < 10) { minutes = `0${minutes}`; } else if (seconds < 10) { seconds = `0${seconds}`; } if (seconds > 0) { time--; } else { clearInterval(SI); } document.getElementById('div').innerHTML = `${minutes}:${seconds}`; } let time = 119; let SI = setInterval(() => { timer(); }, 1000);
 <div id="div"></div>

Solved.解决了。 Even I don't know how the minutes are running without a code for it Oo即使我不知道没有代码的情况下分钟是如何运行的 Oo

let time=123;
function timer(){
    let minutes=Math.floor(time/60),
        seconds=time%60;
    /*if(minutes<10){
        minutes=`0${minutes}`;
    }if(seconds<10){
        seconds=`0${seconds}`;
    }*/
    if(time>0){
        time=time-1;
    }
    document.getElementById("div").innerHTML=`${minutes}:${seconds}`;
}
setInterval(()=>{
    timer();
},1000);
<div id="div"></div>

Your script should be setInterval(timer,1000) for the timer component.您的脚本应该设置为计时器组件的setInterval(timer,1000)

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

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