javascript countdown drift
I have been coding a penny auction site and running into a problem with
the countdowns. The starting time seems to be a little different on
different machines (usually a discrepancy of about a second, but sometimes
2 or 3), which obviously is a big issue for bidders. I'm thinking a big
part of the answer is simply network lag, but (a) are there other factors
involved? and (b) is there a way to correct for network lag somehow?
I've tried hitting the server via an Ajax call every second, and that
works well enough (though there's always a bit of lag) but I'd rather not
have to do that because it'll be hard on the server.
JavaScript development is not my forte, so I'd appreciate any tips and
feedback!
Here's my code, as generated on the server
jQuery(document).ready(function() {
var aid = " . $aid . ";
var loadTime = Math.floor(jQuery.now()/1000);
//alert(loadTime);
serverTime = " . time() . ";
var clockDiff = loadTime - serverTime;
var diff;
auctionExpirationValue" . $aid . " = " . $expiry . ";
var newServerTime = setInterval(function() {
diff = window['auctionExpirationValue' + aid] -
Math.floor((jQuery.now())/1000) + clockDiff;
diff_string = parse_countdown(diff);
jQuery('#auction-expiry').html(diff_string);
},1000);
});
the clockDiff variable is to account for any clock differences between the
user's machine and the server. Obviously, if one machine is ahead or
behind the user would see different values in the countdown.
As you can see, the code loops every second (or, more or less every
second, I understand it's not exact), calculates the difference between
now and the auction expiry (compensating with clockDiff), formats it and
displays it. Pretty simple. The auctionExpirationValue*** global variable
is used to store the auction expiry time locally as a timestamp.
My client has also informed me that on his iPad, the countdown would
sometimes drift a little, in addition to the original discrepancy. What's
the explanation there?
No comments:
Post a Comment