Adding milliseconds to timer in html

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

Answers:

Answer

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>

Answer

Always late to the party but here's one I made earlier. Seems a shame to waste it.

http://jsfiddle.net/dy25nce7/

function countdownTimer(el,duration){
    var exp = Date.now() + duration;//expires in now + duration milliseconds

    //callback using window.requestAnimationFrame if available else setTimeout at 60fps:
    var rAF = window.requestAnimationFrame || function(callback){window.setTimeout(callback,1000/60);};

    //left-pad with leading zeros
    function pad(n,s){
        s = s||2;
        return ("00000"+n).substr(-s);
    }

    //The loopy bit:
    //note the use of a bitwise right-shift to convert to int (http://jsperf.com/number-vs-parseint-vs-plus/39)
    (function update() {
      var n = Date.now(),
          e = (exp-n),
          ms= (e%1000),
          s = ((e/1000)%60) >> 0,
          m = ((e/(1000*60))%60) >> 0,
          h = ((e/(1000*60*60))%24) >> 0;
      if (e > 0) {
          el.innerHTML = pad(h)+":"+pad(m)+":"+pad(s)+":"+pad(ms,3);
          rAF(update);
      } else {
          el.innerHTML = "00:00:00:000";
      }
    })();//IIFE (Immediately-Invoked Function Expression)

};

countdownTimer(document.getElementById('timer'),10000);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.