Tutorial :ServerTime with Jquery



Question:

I need a js code for always getting the server time in a webpage. This code is working but not get the time dynamically. Code gets time one time while webpage loading.

$(document).ready(function() {                   $.ajax({                      type: "POST",                      url: "GenericWCF.svc/GetSystemTime",                      data: "{}",                    contentType: "application/json; charset=utf-8",                      dataType: "json",                      success: function(bs) {                          $("#systemTime").text(bs.d);                    }                 });    });  


Solution:1

You need to use the window.setInterval method to call your function which performs your ajax call.

The window.setInterval method calls a function every X milliseconds repeatedly, until a call to window.clearInterval is called. Note that window.setInterval is "standard" javascript rather than jQuery.

For example:

window.setInterval('yourfunction()', 1000);    function yourfunction()  {     // your ajax call here.  }  

Will call your ajax function every 1000 milliseconds (every second).


Solution:2

As @CraigTP said you have to use a timer to continuously update the time.

But why using ajax to get the time? It'll be better to just get the server time upon rendering, and then update it in the client every minute, without ajax. Just add to it a minute every minute.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »