Skip to content

Instantly share code, notes, and snippets.

@postpostscript
Last active June 9, 2016 15:04
Show Gist options
  • Save postpostscript/8d8adb6ed0e0a880ade0d2fbd6c3f0bd to your computer and use it in GitHub Desktop.
Save postpostscript/8d8adb6ed0e0a880ade0d2fbd6c3f0bd to your computer and use it in GitHub Desktop.
$(function() {
function render($el, timer, timestamp) {
var seconds = Math.round((timestamp - timer.timestamp) / timer.delay);
var minutes = (seconds - seconds % 60) / 60;
seconds = seconds % 60;
if (String(seconds).length == 1) {
seconds = '0' + seconds;
}
var timeDisplay = minutes + ':' + seconds;
if (minutes >= 60) {
var hours = (minutes - minutes % 60) / 60;
minutes = minutes % 60;
if (String(minutes).length == 1) {
minutes = '0' + minutes;
}
timeDisplay = hours + ':' + minutes + ':' + seconds;
}
$($el).text(timeDisplay);
}
$('.timer').each(function() {
var $this = $(this);
var timer = Timer({
timestamp: Number($this.attr('data-timestamp')),
});
timer.afterTick = render.bind($this, $this, timer);
$this.data('timer', timer.tick());
});
});
function extend() {
var result = arguments[0];
for(var i = 1; i < arguments.length; i++) {
for(var key in arguments[i]) {
result[key] = arguments[i][key];
}
}
return result;
}
function Timer() {
var _this = {};
return extend.bind(this, _this, {
timestamp: new Date().getTime(),
timeout: -1,
delay: 1000,
tick: function(timestamp) {
var timestamp = timestamp || this.now();
this.timeout = setTimeout(function() {
var timestamp = _this.now();
_this.tick(timestamp);
_this.afterTick(timestamp);
}, this.nextTickDelay(timestamp));
return this;
},
stop: function() {
clearTimeout(this.timeout);
return this;
},
nextTickDelay: function(timestamp) {
return this.delay - ((timestamp - this.timestamp) % this.delay);
},
now: function() {
return new Date().getTime();
},
afterTick: Function(),
}).apply(this, arguments);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment