So I tried to implement an accurate timer in Javascript via the answer under the accepted answer in this SO post. The only change I made was to initialize an event_last_occurrence_time which occurs on some Javascript event initialization such as the opening of a lightbox. The idea is that every 4 seconds, I'll close a lightbox that is popped up when the page is first opened.
What I notice is that the lightbox actually closes in about 1-2 seconds as opposed to 4 seconds on the first instance of the browser launch. So I did console.log(elapsed-event_last_occurrence_time) and kept track on my stopwatch - it seems that the timing mechanism below moves faster than real-world time on initialization at least (I can see this via the console.log - it jumps to 5-10 seconds while my stopwatch is still around ~2 seconds.
1) Is this just the nature of the timing mechanisms in Javascript or is there an obvious flaw in the algorithm below that I'm missing?
var start = new Date().getTime(),
time = 0,
elapsed = '0.0'
event_last_occurrence_time = elapsed;
function instance()
{
time += 100;
elapsed = Math.floor(time / 100) / 10;
if(Math.round(elapsed) == elapsed) { elapsed += '.0'; }
if ((elapsed-event_last_occurrence_time)%4==0) { $.lightBox.close() }
document.title = elapsed;
var diff = (new Date().getTime() - start) - time;
window.setTimeout(instance, (100 - diff));
}
window.setTimeout(instance, 100);
$("#some_id").click(function(e)
{
$.lightBox({
onOpen: function ()
{
instance();
event_last_occurrence_time = elapsed;
}
});
});