Why is the length of the second wrong?

I have a javascript program like:

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

In my code, you can see that I multiply by 1000 and then divide by 1000, and this is because I want to increment by a millisecond every time, but show the number of seconds in the output of the div. But when I opened the page in which this code was, the second is not really the "second", if you understand what I mean. It is currently three times longer than usual, and I don’t know why.

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

thank

Lucas

+5
source share
4 answers

, JavaScript setInterval , , . , 1 waaaay (?) .

, , , .

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);
+4

, . , JavaScript , .

" OSX , , Windows 15 ".

. , , , . 1 , , . , ( ), .

, , 4 , ( ), ( ).

+3

, , , . .

. http://jsfiddle.net/NGTXU/

setInterval(function () {
   document.getElementById("time").value++;
},1000);
+1

since setIntervalaccepting an argument like milisecond, I think you should replace 1with1000

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

All Articles