Displaying different computer time on a web page using javascript?

I am working on a very time sensitive web application. One of the business rules given to me is that the behavior of an application should always depend on the time on the web server, regardless of the time on the client’s watch. To make this clear to the user, I was asked to display the server 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 to updateDisplayCallbackis a simple function to display the date on a web page.

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

, . , , ! , - .

, - ?

+5
3

. , . , , .

, , .

, -.

, , setInterval(..., 1000) , - . , "" , , .

, "" .

:

(1) AJAX , . . - . .

(2) tick. , tick, , tick. , setTimeout, .

(3) , tick , , , (1). , , , , . . , , setTimeout (, , ), .

0

Javascript setInterval , .

:

  • ( , )
  • (-)
  • ,

: , , 2 . , , .

+6

setInterval . 1000ms , JavaScript .

new Date().getTime(), , .

Allowed minimum interval browsers matter 10.

+2
source

All Articles