How to create an accurate timer in javascript?

前端 未结 10 2389
一个人的身影
一个人的身影 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:35

    This is an basic implementation of a simple timer. note: .timer is the class where the timer is to be shown, and done function is your implementation which will trigger after timers completion

    function TIMER() {
            var fiveMinutes = 60 * 5,
            display = document.querySelector('.timer');
    
            startTimer(fiveMinutes, display);
        }
        var myInterval;
        function startTimer(duration, display) {
            var timer = duration, minutes, seconds;
    
            myInterval = setInterval(function () {
                minutes = parseInt(timer / 60, 10)
                seconds = parseInt(timer % 60, 10);
    
                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;
    
                display.textContent = minutes + ":" + seconds;
    
                if (--timer < 0) {
                    clearInterval(myInterval);
                    doneFunction();
                }
            }, 1000);
        }
    

提交回复
热议问题