简单的JavaScript定时器功能

时间:2015-10-30 19:22:21

标签: javascript timer

所以,我写了一个计时器,当页面加载时启动,并在用户点击“完成”按钮时停止

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

我的代码工作正常,我只是想知道是否有更简单/更容易/更快的方式在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);

1 个答案:

答案 0 :(得分:0)

您无法使用com.thinkaurelius.titan.core.TitanException: Could not commit transaction due to exception during persistence 计算时间因为不准确,但您可以使用setInterval计算日期时间开始和日期时间停止的差异(以秒为单位)并更新计时器页面上的div。

JS:

setInterval

HTML:

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();

<强> Check the demo fiddle