Javascript事件基于本地时钟触发 [英] Javascript event triggers based on local clock

查看:73
本文介绍了Javascript事件基于本地时钟触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,一台客户端PC将驱动多个LCD显示器,每个显示一个浏览器窗口。这些浏览器窗口使用jquery显示动画循环中的不同数据。

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.

所以我的问题是 - 我可以触发jquery根据本地PC时钟替换内容吗?

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

例如,每次时钟秒== 0,显示版本1,每次时钟秒== 30,显示版本2等?

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

推荐答案

根据我的经验,这是让计时器尽可能接近时钟时间的最精确方法:

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.

使用 setInterval 会导致其他问题,包括时钟漂移。基于当前时间的计算说明了执行回调本身的时间。

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

您还需要使用 Date()。getTime ()以及确定要显示的动画帧。

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();

工作演示 http://jsfiddle.net/alnitak/JPu4R/

这篇关于Javascript事件基于本地时钟触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆