在计时器html中显示毫秒

时间:2014-10-17 20:08:31

标签: javascript html

如何在html中显示倒数计时器? 目前的代码:

var count=6000;
var counter=setInterval(timer, 1);; //1000 will  run it every 1 second

function timer(){
  count=count-1;

  if (count <= 0){
    clearInterval(counter);
    return;
  }
  document.getElementById("timer").innerHTML=count + " milliseconds"; // watch for spelling
}

将秒转换为ms

function msToTime(s) {
  var ms = s % 1000;
  s = (s - ms) / 1000;
  var secs = s % 60;
  s = (s - secs) / 60;
  var mins = s % 60;
  var hrs = (s - mins) / 60;

  return hrs + ':' + mins + ':' + secs + '.' + ms;
}

我怎么叫出计时器?  仍将计时器显示为ms。我希望它显示为99:00秒而不是9900毫秒。

由于

3 个答案:

答案 0 :(得分:2)

您可以这样做:

var expires = new Date();

expires.setSeconds(expires.getSeconds() + 60); // set timer to 60 seconds
var counter = setInterval(timer, 1);

function timer() {
    var timeDiff = expires - new Date();

    if (timeDiff <= 0) {
        clearInterval(counter);
        document.getElementById("timer").innerHTML = "00:00";
        return;
    }

    var seconds = new Date(timeDiff).getSeconds();
    var milliSeconds = (new Date(timeDiff).getMilliseconds() / 10).toFixed(0);

    var seconds = seconds < 10 ? "0" + seconds : seconds;
    var milliSeconds = milliSeconds < 10 ? "0" + milliSeconds : milliSeconds;

    document.getElementById("timer").innerHTML = seconds + ":" + milliSeconds; // watch for spelling
}

这里我从javascript Date()函数设置开始时间,然后在timer()函数中计算与当前时间的差异。

请在此处查看:JSFiddle

答案 1 :(得分:1)

如果它是JavaScript并且与Time有关,我使用moment.js http://momentjs.com

Moment默认为毫秒,因为它是第一个参数:

moment(9900).format("mm:ss");是9秒,显示为:00:09

http://plnkr.co/edit/W2GixF?p=preview

答案 2 :(得分:0)

这是一个实际上准确的计时器(因为它实际上显示了正确的剩余时间)。无论你要求什么,setInterval都不会每1毫秒调用一次,因为实际的分辨率并不高。您也不能依赖一致性,因为它不是在实时环境中运行。如果您想跟踪时间,请比较Date个对象:

&#13;
&#13;
var count=60000;
var start = new Date();
var counter=setInterval(timer, 1); //1000 will  run it every 1 second

function timer(){
  var left = count - (new Date() - start);

  if (left <= 0){
    clearInterval(counter);
    document.getElementById("timer").innerHTML = msToTime(0) + " seconds";
    return;
  }
  document.getElementById("timer").innerHTML = msToTime(left) + " seconds"; // watch for spelling
}

function msToTime(s) {
  var ms = s % 1000;
  s = (s - ms) / 1000;
  return s + ':' + pad(ms, 3);
}

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
&#13;
<div id='timer'></div>
&#13;
&#13;
&#13;

借用@ Cheery的小提琴作为起点。

相关问题