Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the length of a second correct?

I have a javascript program like such:

function addtime() {
  curtime = document.getElementById("time").value * 1000;
  curtime += 1;
  document.getElementById("time").value = curtime / 1000;
}
setInterval(function () {
  addtime();
}, 1);

You may see in my code that I am multiplying by 1000 and then dividing by 1000, and this is because I want to increment by a millisecond every time, but show the amount of seconds in the "time" output div. But when I opened the page which had this code in it, a second is not actually "a second", if you understand what I mean. It is currently three times longer than the normal second, and I don't know why.

So what is the problem in my code, and what can I do to fix it?

Thanks

Lucas

like image 398
Lucas Avatar asked Feb 20 '23 20:02

Lucas


2 Answers

The problem is that JavaScript is not guaranteed to call setInterval at exactly the time you specify, but at the first opportunity it has after that time has passed. Also, 1ms is waaaay under the resolution of a lot of (all?) browsers.

To do this properly, get the start time, then find out the elapsed milliseconds by subtracting the current time.

var start = new Date();
var update = function() {
    var now = new Date();
    var elapsed = now - start;
    // now you can do something with `elapsed`,
    // like stuff it into the UI
};
setInterval(update, 100);
like image 126
Amadan Avatar answered Feb 28 '23 15:02

Amadan


Here's a video where J. Resig explains how JavaScript has innacurate timers, in context to his presentation about using timers in testing.

"OSX timers are precise, to the milisecond. But in Windows, the timer is only updated every 15ms."

here's another article by N. Zakas, that points out that timer resolution is different in some cases and it depends on the browser also. 1ms resolution is fast, but it will take a big bite in CPU processing, that's why browsers pull it back. As far as i know, browsers throttle down timers (as well as rendering), when the tab is not in focus.

i see this in chrome a lot, especially in slow PCs where opening 4 tabs at once of the same page, only the one in focus renders first (clockwise fast icon), while the others continue to load (counter-clockwise loading icon).

like image 45
Joseph Avatar answered Feb 28 '23 13:02

Joseph