How to create an accurate timer in javascript?

前端 未结 10 2299
一个人的身影
一个人的身影 2020-11-22 01:32

I need to create a simple but accurate timer.

This is my code:

var seconds = 0;
setInterval(function() {
timer.innerHTML = seconds++;
}, 1000);
         


        
10条回答
  •  一整个雨季
    2020-11-22 02:36

    Doesn't get much more accurate than this.

    var seconds = new Date().getTime(), last = seconds,
    
    intrvl = setInterval(function() {
        var now = new Date().getTime();
    
        if(now - last > 5){
            if(confirm("Delay registered, terminate?")){
                clearInterval(intrvl);
                return;
            }
        }
    
        last = now;
        timer.innerHTML = now - seconds;
    
    }, 333);
    

    As to why it is not accurate, I would guess that the machine is busy doing other things, slowing down a little on each iteration adds up, as you see.

提交回复
热议问题