在html中为计时器添加毫秒 [英] Adding milliseconds to timer in html

查看:608
本文介绍了在html中为计时器添加毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以将毫秒添加到我的计时器吗?



我目前使用这个计时器,但它只能以秒为单位计数。

  var count = 99; 
var counter = setInterval(timer,1000); // 1000会每1秒运行一次

函数timer(){
count = count-1;

if(count <= 0){
clearInterval(counter);
return;
}
document.getElementById(timer)。innerHTML = count +seconds; //注意拼写
}

谢谢



只需使用 window.requestAnimationFrame 代替,并显示传递给该函数的时间与计时器的参考开始时间之间的差异。
$ b

var timer = document.getElementById('timer'); var expires = + new Date()+ 10000;(function update(){var now = + new Date(); var togo = expires - now; if(togo> 0) {timer.innerHTML = togo; window.requestAnimationFrame(update);} else {timer.innerHTML = 0;}})();

 < div id =timer>< / div>  


Is there any way i could add milliseconds to my timer?

I'm currently using this timer but its only counting in seconds.

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

    function timer(){
      count=count-1;

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

Thanks

解决方案

Timers won't run with millisecond accuracy - not only is that below the standard JS minimum timeout, timer events can queue up and all sorts of other issues. In any event (no pun intended) you can't actually see a timer count up 1000 times a second.

Just use window.requestAnimationFrame instead and show the difference between the time passed to that function and the reference start time of the timer.

var timer = document.getElementById('timer');

var expires = +new Date() + 10000;

(function update() {
  var now = +new Date();
  var togo = expires - now;
  if (togo > 0) {
    timer.innerHTML = togo;
    window.requestAnimationFrame(update);
  } else {
    timer.innerHTML = 0;
  }
})();

<div id="timer"></div>

这篇关于在html中为计时器添加毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆