简体   繁体   中英

Simple JavaScript Timer Function

So, I've written a timer to start when the page loads, and to stop when the user clicks a "finished" button

    <br><button id = "finish" onclick = "stopTimer();">Done</button>

My code works fine, I was just wondering if there's a simpler/easier/faster way to implement a timer in Javascript?

//Stop timer function
function stopTimer() {
    clearInterval(time);
}

//Start timer function
var secTime = 0,
      minTime = 0,
      hourTime = 0;

var time =  setInterval(function(){
    var maxSec = 59,
        maxMin = 59,
        maxHour = 59;
if(secTime > maxSec){
      minTime++;
      if(minTime > maxMin){
        hourTime++;
        if(hourTime > maxHour){
          hourTime = 0;
          minTime = 0;
          secTime = 0;
        }
        minTime = 0
      }
      secTime = 0;
    }    
        var newSec = (secTime.toString().length == 1) ? '0' + secTime : secTime,
            newMin = (minTime.toString().length == 1) ? '0' + minTime : minTime,
            newHour = (hourTime.toString().length == 1) ? '0' + hourTime : hourTime;

        document.getElementById('timer').innerHTML = newHour + ':' + newMin + ':' + newSec;

    secTime++;    
}, 1000);

You can't count the time using setInterval because is not precise, but you can use the setInterval to calculate the difference (in seconds) of the datetime start and datetime stop and update the timer div on the page.

JS:

var dateTimeStart = new Date();
var intervalId;
var seconds = 0;

function start(){
    updateTimer();
    intervalId = setInterval(function(){
      seconds = Math.floor((new Date() - dateTimeStart) / 1000);
        updateTimer();
    }, 1000);
}

function stop(){
    clearInterval(intervalId);
}

function updateTimer(){
    var date = new Date(1970, 0, 1);
    date.setSeconds(seconds);
    document.getElementById('timer').innerHTML = format(date);
}

function format(date){
  return twodigits(date.getHours()) + ':' + twodigits(date.getMinutes()) + ':' + twodigits(date.getSeconds());
}

function twodigits(number){
    var str = '0' + number;
    return str.substr(-2);
}

function action(name){
    document.getElementById('action').innerHTML = name;
}

start();

HTML:

<div id="timer"></div>
<button type="button" onclick="stop();">STOP</button>

Check the demo fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM