Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me how I can able to create an accurate timer in JavaScript? I was trying with the below code but it is not accurate.

var seconds = 0;

setInterval(function() {

timer.innerHTML = seconds++;

}, 1000);

Can anyone know what is wrong with this code?

1 Answer

0 votes
by (26.7k points)

Basically, you are using setTimeout() or setInterval() function which are not accurate. Instead of using those, try with the date object. Below is the code:

var interval = 1000; // ms

var expected = Date.now() + interval;

setTimeout(step, interval);

function step() {

    var dt = Date.now() - expected; // the drift (positive for overshooting)

    if (dt > interval) {

        // something really bad happened. Maybe the browser (tab) was inactive?

        // possibly special handling to avoid futile "catch up" run

    }

    … // do what is to be done

    expected += interval;

    setTimeout(step, Math.max(0, interval - dt)); // take into account drift

}

I hope this will help.

Want to know more about Java? Prefer this tutorial on Java Tutorial.

Want to become a Java Expert? Join Java Course now!!

Related questions

0 votes
1 answer
asked Apr 4, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Mar 15, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer
asked Jan 28, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer

Browse Categories

...