Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript event triggers based on local clock

I have a scenario where one client PC will be driving multiple LCD displays, each showing a single browser window. These browser windows show different data which is on an animated cycle, using jquery.

I need to ensure that both browsers can be synched to rotate at exactly the same time, otherwise they'll animate at different times.

So my question is - can I trigger jquery to alternate the content based on the local PC clock?

eg each time the clock seconds == 0, show version 1, each time clock seconds == 30, show version 2 etc?

like image 478
hud Avatar asked Jan 09 '12 21:01

hud


1 Answers

This is (in my experience) the most precise way of getting timers to trigger as closely as possible to a clock time:

// get current time in msecs to nearest 30 seconds
var msecs = new Date().getTime() % 30000;

// wait until the timeout
setTimeout(callback, 30000 - msecs);

Then, in the callback, once everything is done, do the same again to trigger the next event.

Using setInterval causes other problems, including clock drift. The calculation based on the current time accounts for the time executing the callback itself.

You'll still also need to use Date().getTime() as well to figure out which frame of your animation to show.

The whole thing would look something like this:

function redraw() {
    var interval = 30000;

    // work out current frame number
    var now = new Date().getTime();
    var frame = Math.floor(now / interval) % 2; // 0 or 1

    // do your stuff here
    .. some time passes

    // retrigger
    now = new Date().getTime();
    setTimeout(redraw, interval - (now % interval));
}

redraw();

working demo at http://jsfiddle.net/alnitak/JPu4R/

like image 113
Alnitak Avatar answered Sep 30 '22 12:09

Alnitak