简体   繁体   中英

setInterval doesn’t work continuously and stops after first iteration

The start is 01:59 . When I refresh the page, it becomes 01:58 and stops on that. It should become 01:59 , then 01:58 , then 01:57 etc.

 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. Move the initialization outside the function.

Also, you've forgot to remove 1 second from the time variable after the function call time-- ;

 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

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.

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.

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