1

I've modified the code from SO, provided by SLaks so make it work even if the user changes the time on his computer.

The time for <div id="timer"></div> still showing the real time since the page was loaded (even if the user changes the time on his computer).

When time changed, the alert appears (please see the code below). The problem is: once time is changed, the alert appears the infinite number of times every second (but only one time is expected). Why is this happening?

$(document).ready(function () {
    var start = new Date;
    var end = (new Date - start) / 1000;
    setInterval(function () {
        if (Math.abs(end - (new Date - start) / 1000 )>1) {
            start = new Date - end * 1000;
            alert(Math.abs(end - (new Date - start) / 1000 ));
        }
        end = (new Date - start) / 1000;

        $('#timer').text(end + " Seconds");
    }, 100);
});
4

1 回答 1

2

这实际上非常简单 - 脚本执行会暂停,直到消息框关闭。当您关闭它时,计时器已经延迟并且条件再次为真。您可以通过复制该alert[...]行自行测试:如果您关闭第一条消息的速度足够快,则第二条消息将显示低于 1 的内容。

只需alert用一些基于 HTML 的浮动窗口替换,一切都会好起来的。

于 2013-01-12T23:20:08.123 回答