Created
February 23, 2012 22:01
-
-
Save weisjohn/1895291 to your computer and use it in GitHub Desktop.
a simple jQuery based ticker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a simple utility function for pretty printing | |
function pad(number, length) { | |
var str = '' + number; | |
while (str.length < length) { | |
str = '0' + str; | |
} | |
return str; | |
} | |
var service_time = null, // time on the server | |
sync = 0, // the difference between server and client time | |
party = new Date("Thu, 06 Mar 2012 17:00:00 GMT-0400"), // time of the event | |
times = [], // used for "pretty" printing | |
countdown_milliseconds = 0; // # of milliseconds between "now" and party | |
$("body").bind('$ready', function () { | |
var $clock = $("#clock"); // jQuery reference to DOM node for the clock | |
// build a clock... | |
function tick() { | |
// tick the clock, diff, subtract from event time | |
countdown_milliseconds = party.getTime() - (sync + (new Date()).getTime()); | |
if (countdown_milliseconds > 0) { | |
times = []; | |
// step over days, hours, minutes, seconds and pick them off of the countdown | |
$.each([(1000 * 60 * 60 * 24), (1000 * 60 * 60), (1000 * 60), 1000], function (i, unit) { | |
times.push( pad( Math.floor(countdown_milliseconds / unit) , 2) ); | |
countdown_milliseconds %= unit; | |
}); | |
// pretty "clock" printing | |
$clock.html("-" + times.join(":")); | |
// one-eigth of a second iterations | |
setTimeout(tick, 125); | |
} else { | |
// hide the countdown, as we've just passed the threshold | |
$clock.parent().hide(); | |
} | |
}; | |
$.ajax({ | |
url: "/services/util/time_servlet.jsp?type=current_server_time", | |
success: function (data) { | |
console.log("data.currentServerTime", data.currentServerTime); | |
console.log("new Date(server)", new Date(data.currentServerTime)); | |
console.log("new Date() ", new Date()); | |
// store the difference between the client time and the server time | |
sync = (new Date(data.currentServerTime)).getTime() - (new Date()).getTime(); | |
console.log("sync", sync); | |
tick(); | |
}, | |
failure: function () { | |
console.log('failure'); | |
}, | |
dataType: "json", | |
cache: false | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment