Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Is this timer reliable?

Today I was introduced to the world of Web Workers in JavaScript. This made me rethink about timers. I used to program timers the ugly way, like this.

var time = -1;
function timerTick()
{
    time++;
    setTimeout("timerTick()",1000);
    $("#timeI").html(time);
}

I know this could be improved by saving the date when you start the timer, but I've never been a fan of that.

Now I came up with a method using Web Workers, I did a little benchmark and found it much more reliable. Since I am not an expert on JavaScript I would like to know if this function works correct or what problems it might have thanks in advance.

My JavaScript code (please note I use JQuery):

$(function() {
    //-- Timer using web worker. 
    var worker = new Worker('scripts/task.js'); //External script
    worker.onmessage = function(event) {    //Method called by external script
        $("#timeR").html(event.data)
    };
};

The external script ('scripts/task.js'):

var time = -1;
function timerTick()
{
    time++;
    setTimeout("timerTick()",1000);
    postMessage(time);
}
timerTick();

You can also view a live demo on my website.

like image 642
Daan Avatar asked Dec 22 '22 05:12

Daan


1 Answers

If you're trying to reliably display seconds ticking by, then the ONLY reliable way to do that is to get the current time at the start and use the timer ONLY for updating the screen. On each tick, you get the current time, compute the actual elapsed seconds and display that. Neither setTimeout() nor setInterval() are guaranteed or can be used for accurately counting time.

You can do it like this:

var start = +(new Date);
setInterval(function() {
    var now = +(new Date);
    document.getElementById("time").innerHTML = Math.round((now - start)/1000);
}, 1000);

If the browser gets busy and timers are erratically spaced, you may get a slightly irregular update on screen, but the elapsed time will remain accurate when the screen is updated. Your method is susceptible to accumulating error in the elapsed time.

You can see this work here: http://jsfiddle.net/jfriend00/Gfwze/

like image 107
jfriend00 Avatar answered Dec 28 '22 22:12

jfriend00