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