开发者

Time to start a counter on client-side

I'm developing an web application using asp.net mvc, and i need to do a stopwatch (chronometer) (with 30 seconds preprogrammed to start in a certain moment) on client-side using the time of the server, by the way, the client's clock can't be as the server's clock. So, i'm using Jquery to call the server by JSon and get 开发者_开发百科the time, but it's very stress because each one second I call the server to get time, something like this:

$(function() {
  GetTimeByServer();
});

function GetTimeByServer() {
  $.getJSon('/Home/Time', null, function(result) {
    if (result.SecondsPending < 30) {
      // call another function to start an chronometer
    } else {
      window.SetTimeout(GetTimeByServer, 1000); //call again each 1 second!
    }
  });
}

It works fine, but when I have more than 3 or 4 call like this, the browser slowly but works! I'd like to know, how improve more performace in client side, or if is there any way to do this... is there any way to client listen the server like a "socket" to know if the chronometer should start...

PS: Sorry for my english!

thanks Cheers


Felipe, On page load get the server time and also the Client Side time. and use the two in reference to determine what the server time is on the server side without using AJAX call every time. Sorry for the excess of suedo code but it shouldnt be too hard.

var ServerTimeReference;
var ClientTimeReference;
function InitializeTime()
   $.getJSon('/Home/Time', null, function (result) {
       ServerTimeReference = result.ServerTime; //convert to js time 
       ClientTimeReference = new Date();
     });

function GetServerTime() { 
     var TimeDifference = //get the difference between server and Client time
     var CurrentClientDateTime = new Date();
     var CurrentServerTime = // using timedifference and CurrentClientDateTime calculate ServerTime
     return CurrentServerTime;
} 


I would do all of the time checking on the client side. You are already using jQuery, just use a timer plugin. I've had good success with this one.


If you really want to use it like this, you basically got this options:

  • Use AJAX polling (COMET)
  • Use HTML5 WebSockets

I don't fully understand why you just send a value to the client and not just a "GO" string if the client should start doing anything. Either way, you don't have to poll that every second (I mean come on, if your local PC's clock is THAT wrong would be a bad sign). So it should be enough to 'syncronize' every 10 seconds for instance (which also is pretty fast).

So my basic strategy would be, call a backend function which tells my client, how much time is left to go and setup a setTimeout on that value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜