Smith5727
Smith5727

Reputation: 785

Create javascript timer with server sync

I want to show the current time (including seconds) with a javascript timer that increments every second. But I cannot trust the system time so I want to initialize the javascript function with a timestamp from my server and then just add one second with a setTimeout to the initialized timestamp that was passed into the function. Then I learned that setTimeout is not really accurate so the clock would show several minutes off after a while.

So my idea is to make that every 60 seconds it will sync up the time with the server that gave the initial timestamp. But then I started worry that it will be a lot of memory leaks since the setTimeout method is actually recursive, my suggestion method would look like this in big picture:

function runClock(currentTime) {

    var now = new Date(Date.parse(currentTime));

   // 1. write now variable to some DOM element

   // 2. check if we need to sync time with server (counter variable or similar to see if approx 60sec has passed) 
   //   and if so do an $.ajax call to the server and update "now" variable with timestamp from the server

    t = setTimeout(function () {
        now.setSeconds(now.getSeconds() + 1);
        runClock(now);
    }, 1000);

}

Can anyone guide me if this is right method and if so adjust my method so it wont create memory leaks due to callbacks and recursion.

Upvotes: 0

Views: 405

Answers (1)

VeteranSlayer
VeteranSlayer

Reputation: 404

Actually, i think you mean the method setInterval. I believe that you should use a counter that has an initial value of 1. After every call of the interval method the counter should increase by one and then you can check if counter surpassed the value 60 and only then make an ajax call and restart everythink.

It should look something like this

var counter = 1;
var timer = 0;
yourAjaxCall();
var t = setInterval(function(){
    //do client side stuff with time

    //after you done check if time needs to be fetched from server {60 seconds passed}
    counter++;
    if(counter >= 60){
        counter = 1;
        yourAjaxCall();
    }
}, 1000);

function yourAjaxCall(){
    $.ajax({
        url: 'yoururl',
        type: 'post',
        success: function(response){
            timer = response;
        }
    });
}

Upvotes: 1

Related Questions