How to create an accurate timer in javascript?

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

    Bergi's answer pinpoints exactly why the timer from the question is not accurate. Here's my take on a simple JS timer with start, stop, reset and getTime methods:

    class Timer {
      constructor () {
        this.isRunning = false;
        this.startTime = 0;
        this.overallTime = 0;
      }
    
      _getTimeElapsedSinceLastStart () {
        if (!this.startTime) {
          return 0;
        }
      
        return Date.now() - this.startTime;
      }
    
      start () {
        if (this.isRunning) {
          return console.error('Timer is already running');
        }
    
        this.isRunning = true;
    
        this.startTime = Date.now();
      }
    
      stop () {
        if (!this.isRunning) {
          return console.error('Timer is already stopped');
        }
    
        this.isRunning = false;
    
        this.overallTime = this.overallTime + this._getTimeElapsedSinceLastStart();
      }
    
      reset () {
        this.overallTime = 0;
    
        if (this.isRunning) {
          this.startTime = Date.now();
          return;
        }
    
        this.startTime = 0;
      }
    
      getTime () {
        if (!this.startTime) {
          return 0;
        }
    
        if (this.isRunning) {
          return this.overallTime + this._getTimeElapsedSinceLastStart();
        }
    
        return this.overallTime;
      }
    }
    
    const timer = new Timer();
    timer.start();
    setInterval(() => {
      const timeInSeconds = Math.round(timer.getTime() / 1000);
      document.getElementById('time').innerText = timeInSeconds;
    }, 100)

    Elapsed time: 0s

    The snippet also includes a solution for your problem. So instead of incrementing seconds variable every 1000ms interval, we just start the timer and then every 100ms* we just read elapsed time from the timer and update the view accordingly.

    * - makes it more accurate than 1000ms

    To make your timer more accurate, you would have to round

提交回复
热议问题