Search code examples
javascripthtmltimer

Run a Function For Each Milliseconds


I am trying to run a function for each milliseconds, In order to achieve so, I just preferred setInterval concept in javascript. My code is given 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 am testing the result with a real clock, the real clock requires 1000 milliseconds to complete 1 second, at the same time the result require more than 1000 milliseconds to complete a second.

DEMO

Can anybody tell me,

Is there any mistakes with my code? If yes then tell me, How to display milliseconds accurately.?


Solution

  • There are no mistakes in your code, but JavaScript timers (setInterval and setTimeout) are not precise. Browsers cannot comply with such a short interval. So I'm afraid there is no way to precisely increment the milliseconds by one, and display the updates, on a web browser. In any case, that's not even visible to the human eye!

    A precise workaround would involve a larger interval, and timestamps to calculate the elapsed time in milliseconds:

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