Skip to content

Instantly share code, notes, and snippets.

@remino
Created January 5, 2012 23:24
Show Gist options
  • Save remino/1567951 to your computer and use it in GitHub Desktop.
Save remino/1567951 to your computer and use it in GitHub Desktop.
TimeCounter: jQuery plugin object to display count from certain time
(function($) {
function TimeCounter($clock, $start) {
var that = this;
this.$clock = $clock;
this.$start = $start;
this.since = new Date(this.$start.text());
self.setTimeout(function() { that.init(); }, 200);
}
// FIXME Use DateDiff object instead.
// SEE https://gist.github.com/1563963
TimeCounter.prototype.convert = function(ms) {
var d, h, m, s, t;
s = Math.floor(ms / 1000);
m = Math.floor(s / 60);
s = s % 60;
h = Math.floor(m / 60);
m = m % 60;
d = Math.floor(h / 24);
h = h % 24;
t = this.padLeft(d, 0, 3);
t += ':' + this.padLeft(h, 0, 2);
t += ':' + this.padLeft(m, 0, 2);
t += ':' + this.padLeft(s, 0, 2);
return t;
};
TimeCounter.prototype.init = function() {
this.print();
};
TimeCounter.prototype.padLeft = function(str, chr, len) {
var padding = '';
str = str + '';
for(var i = 0; i < len - str.length; i++) {
padding += chr;
}
return padding + str;
};
TimeCounter.prototype.print = function() {
var that = this;
var clock = this.convert(new Date() - this.since);
this.$clock.text(clock);
self.setTimeout(function() { that.print(); }, 50);
};
$.fn.timeCounter = function($start) {
if(!this.data('timeCounter'))
this.data('timeCounter', new TimeCounter(this, $start));
return this.data('timeCounter');
};
/* Usage example */
// $(document).ready(function() {
// $('.post strong').timeCounter($('.post em'));
// });
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment