Run function for every millisecond

I am trying to run a function for every millisecond. To achieve this, I just preferred the concept setIntervalin javascript. My code is below

HTML:

<div id=test>0.0</div>

Script:

var xVal = 0;
var xElement = null;

xElement = document.getElementById("test");
var Interval = window.setInterval(startWatch, 1);


function startWatch(){

    xVal += 1;
    xElement.innerHTML = xVal;

}

so the above code is working fine. But while I'm testing the result with a real watch, a real watch needs 1000 milliseconds to complete 1 second, and at the same time it takes more than 1000 milliseconds to complete.

Demo

Can anyone tell me

Are there any errors with my code? If so, tell me how to accurately display milliseconds.?

+4
source share
5 answers

, JavaScript (setInterval setTimeout) . . , -. , !

:

var start = new Date().getTime();
setInterval(function() {
    var now = new Date().getTime();
    xElement.innerHTML = (now - start) + 'ms elapsed';
}, 40);
+7

DOM 1000 . 1000 , . :

(function(){
    var xElement = document.getElementById("test");
    var start = new Date;

    (function update(){
      xElement.innerHTML = (new Date - start);

      setTimeout(update, 0);
    })();
}();

​​

+3

, - HTML . 60FPS.

http://jsfiddle.net/3hEs4/3/

var xElement = null;
var startTime = new Date();

xElement = document.getElementById("test");
var Interval = window.setInterval(startWatch, 17);


function startWatch(){
     var currentTime = new Date();
     xElement.innerHTML = currentTime - startTime;   
}

requestanimationframe setInterval.

+2

setInterval, , , , , , , .

, Javascript , setInterval, , , reset . DOM, .

, , , , .

0

Source: https://habr.com/ru/post/1502895/


All Articles