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
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.