Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying another computer's time on a web page using Javascript? [duplicate]

I am working on a very time-sensitive web application. One of the business rules given to me is that the application's behavior must always depend on the time on the web server, regardless of what time is on the client's clock. To make this clear to the user, I was asked to display the server's time in the web application.

To this end, I wrote the following Javascript code:

clock = (function () {
var hours, minutes, seconds;

function setupClock(updateDisplayCallback) {
    getTimeAsync(getTimeCallback);

    function getTimeCallback(p_hours, p_minutes, p_seconds) {
        hours = p_hours;
        minutes = p_minutes;
        seconds = p_seconds;
        setInterval(incrementSecondsAndDisplay, 1000);
    }

    function incrementSecondsAndDisplay() {
        seconds++;
        if (seconds === 60) {
            seconds = 0;
            minutes++;
            if (minutes === 60) {
                minutes = 0;
                hours++;
                if (hours === 24) {
                    hours = 0;
                }
            }
        }
        updateDisplayCallback(hours, minutes, seconds);
    }
}

// a function that makes an AJAX call and invokes callback, passing hours, minutes, and seconds.
function getTimeAsync(callback) {
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetLocalTime",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var date, serverHours, serverMinutes, serverSeconds;
            date = GetDateFromResponse(response);
            serverHours = date.getHours();
            serverMinutes = date.getMinutes();
            serverSeconds = date.getSeconds();
            callback(serverHours, serverMinutes, serverSeconds);
        }     
    })
}

return {
    setup: setupClock
};
})();

The function passed in for updateDisplayCallback is a simple function to display the date on the web page.

The basic idea is that the Javascript makes an asynchronous call to look up the server's time, store it on the client, and then update it once per second.

At first, this appears to work, but as time goes by, the displayed time gets behind a few seconds every minute. I left it running overnight, and when I came in the next morning, it was off by more than an hour! This is entirely unacceptable because the web application may be kept open for days at a time.

How can I modify this code so that the web browser will continuously and accurately display the server's time?

like image 670
Vivian River Avatar asked Mar 29 '13 14:03

Vivian River


2 Answers

Javascript's setInterval is not accurate enough to allow you to keep the time like this.

My solution would be:

  1. Periodically get the server's time in milliseconds (it does not need to be very often as the two clocks will hardly deviate that much)
  2. Get the client time in milliseconds
  3. Calculate the clock deviation between server and client (client-server)
  4. Periodically update the display of the clock by getting the client time and adding the clock deviation

Edit: To be more accurate, you could measure the round trip time of the server's request, divide it by 2 and factor that delay into the clock deviation. Assuming round trips are symmetrical in their duration, this would give a more accurate calculation.

like image 58
Jorge Cardoso Avatar answered Sep 30 '22 16:09

Jorge Cardoso


setInterval is not a reliable way to schedule time critical events. It may take less or more than 1000ms to run your callback depending on how busy JavaScript it is at the moment.

A better approach would be to take a shorter interval and use new Date().getTime() to check if a second has passed.

The minimum interval browsers allow is as high 10.

like image 34
Halcyon Avatar answered Sep 30 '22 17:09

Halcyon