使Javascript计时器显示00占位符

时间:2015-10-05 22:45:11

标签: javascript

var m=0;
var s=0;
var h=0;
var t;

function start(){
    document.getElementById('ms').innerHTML=m;
    document.getElementById('mm').innerHTML=s;
    document.getElementById('mh').innerHTML=h;
    s++;

    if(s==60){
        s=0;
        m++;
    }
    if(m==60){
        m=0;
        h++;
    }
    t= setTimeout("start()",20);
}

function stop(){
    clearTimeout(t);
}

当计数器增加时,它会显示一个数字。不确定如何将时钟格式化为类似于数字时钟,即00:00:00。感谢

1 个答案:

答案 0 :(得分:1)

以下是一个例子:



var m = 0;
var s = 0;
var h = 0;
var t;

function start() {
  var z = '';
  z = (s < 10) ? '0' : '';
  document.getElementById('ms').innerHTML = z + s;
  s++;

  if (s == 60) {
    s = 0;
    z = (m < 10) ? '0' : '';
    document.getElementById('mm').innerHTML = z + m;
    m++;

    if (m == 60) {
      m = 0;
      z = (h < 10) ? '0' : '';
      document.getElementById('mh').innerHTML = z + h;
      h++;
    }
  }
  t = setTimeout(start, 1000);
}

function stop() {
  clearTimeout(t);
}
&#13;
<span id="mh">00</span> : <span id="mm">00</span> : <span id="ms">00</span>
<br>
<br>
<button type="button" onclick="start()">Start</button>
<button type="button" onclick="stop()">Stop</button>
&#13;
&#13;
&#13;