How to create an accurate timer in javascript?

前端 未结 10 2378
一个人的身影
一个人的身影 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 02:24

    I'ma just build on Bergi's answer (specifically the second part) a little bit because I really liked the way it was done, but I want the option to stop the timer once it starts (like clearInterval() almost). Sooo... I've wrapped it up into a constructor function so we can do 'objecty' things with it.

    1. Constructor

    Alright, so you copy/paste that...

    /**
     * Self-adjusting interval to account for drifting
     * 
     * @param {function} workFunc  Callback containing the work to be done
     *                             for each interval
     * @param {int}      interval  Interval speed (in milliseconds) - This 
     * @param {function} errorFunc (Optional) Callback to run if the drift
     *                             exceeds interval
     */
    function AdjustingInterval(workFunc, interval, errorFunc) {
        var that = this;
        var expected, timeout;
        this.interval = interval;
    
        this.start = function() {
            expected = Date.now() + this.interval;
            timeout = setTimeout(step, this.interval);
        }
    
        this.stop = function() {
            clearTimeout(timeout);
        }
    
        function step() {
            var drift = Date.now() - expected;
            if (drift > that.interval) {
                // You could have some default stuff here too...
                if (errorFunc) errorFunc();
            }
            workFunc();
            expected += that.interval;
            timeout = setTimeout(step, Math.max(0, that.interval-drift));
        }
    }
    

    2. Instantiate

    Tell it what to do and all that...

    // For testing purposes, we'll just increment
    // this and send it out to the console.
    var justSomeNumber = 0;
    
    // Define the work to be done
    var doWork = function() {
        console.log(++justSomeNumber);
    };
    
    // Define what to do if something goes wrong
    var doError = function() {
        console.warn('The drift exceeded the interval.');
    };
    
    // (The third argument is optional)
    var ticker = new AdjustingInterval(doWork, 1000, doError);
    

    3. Then do... stuff

    // You can start or stop your timer at will
    ticker.start();
    ticker.stop();
    
    // You can also change the interval while it's in progress
    ticker.interval = 99;
    

    I mean, it works for me anyway. If there's a better way, lemme know.

提交回复
热议问题