How to create an accurate timer in javascript?

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

    I agree with Bergi on using Date, but his solution was a bit of overkill for my use. I simply wanted my animated clock (digital and analog SVGs) to update on the second and not overrun or under run creating obvious jumps in the clock updates. Here is the snippet of code I put in my clock update functions:

        var milliseconds = now.getMilliseconds();
        var newTimeout = 1000 - milliseconds;
        this.timeoutVariable = setTimeout((function(thisObj) { return function() { thisObj.update(); } })(this), newTimeout);
    

    It simply calculates the delta time to the next even second, and sets the timeout to that delta. This syncs all of my clock objects to the second. Hope this is helpful.

    0 讨论(0)
  • 2020-11-22 02:35

    This is an old question but figured I'd share some code I use sometimes:

    function Timer(func, delay, repeat, runAtStart)
    {
        this.func = func;
        this.delay = delay;
        this.repeat = repeat || 0;
        this.runAtStart = runAtStart;
    
        this.count = 0;
        this.startTime = performance.now();
    
        if (this.runAtStart)
            this.tick();
        else
        {
            var _this = this;
            this.timeout = window.setTimeout( function(){ _this.tick(); }, this.delay);
        }
    }
    Timer.prototype.tick = function()
    {
        this.func();
        this.count++;
    
        if (this.repeat === -1 || (this.repeat > 0 && this.count < this.repeat) )
        {
            var adjustedDelay = Math.max( 1, this.startTime + ( (this.count+(this.runAtStart ? 2 : 1)) * this.delay ) - performance.now() );
            var _this = this;
            this.timeout = window.setTimeout( function(){ _this.tick(); }, adjustedDelay);
        }
    }
    Timer.prototype.stop = function()
    {
        window.clearTimeout(this.timeout);
    }
    

    Example:

    time = 0;
    this.gameTimer = new Timer( function() { time++; }, 1000, -1);
    

    Self-corrects the setTimeout, can run it X number of times (-1 for infinite), can start running instantaneously, and has a counter if you ever need to see how many times the func() has been run. Comes in handy.

    Edit: Note, this doesn't do any input checking (like if delay and repeat are the correct type. And you'd probably want to add some kind of get/set function if you wanted to get the count or change the repeat value.

    0 讨论(0)
  • 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);
        }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题