Haradzieniec
Haradzieniec

Reputation: 9340

JQuery Clock / Timer since the page was loaded (even if user changes time on his computer)

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

Upvotes: 1

Views: 958

Answers (1)

gronostaj
gronostaj

Reputation: 2282

It's actually pretty simple - script execution is paused until the messagebox is closed. When you close it, the timer is already delayed and the condition is true again. You can test it yourself by duplicating the alert[...] line: if you close the first message fast enough, the second one will show something below 1.

Just replace alert with some HTML-based floating window and everything will be fine.

Upvotes: 2

Related Questions