Last active
June 9, 2016 15:04
-
-
Save postpostscript/8d8adb6ed0e0a880ade0d2fbd6c3f0bd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
$(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()); | |
}); | |
}); |
This file contains hidden or 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
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; | |
} |
This file contains hidden or 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
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