Skip to content

Instantly share code, notes, and snippets.

@jawdatls
Created May 11, 2015 08:19
Show Gist options
  • Save jawdatls/abfe8fa33e6f5691d92a to your computer and use it in GitHub Desktop.
Save jawdatls/abfe8fa33e6f5691d92a to your computer and use it in GitHub Desktop.
Time Count Up
<div class="counter">
<strong class="h">0</strong>
<span>:</span>
<strong class="m">0</strong>
<span>:</span>
<strong class="s">0</strong>
</div>
<script type="text/javascript">
$(document).ready(function(){
var time = (60 * 60 + 60 * 59 + 55); // start from 1 hour and 59 minutes and 55 seconds
TimeCount.create($('.counter'), time );
});
var TimeCount = function(container,time){
this.container = container;
this.h = this.container.find('.h');
this.m = this.container.find('.m');
this.s = this.container.find('.s');
this.time = time;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.rest = time;
this.ap = null;
}
TimeCount.prototype = {
play : function(){
var that = this;
this.calculation();
this.ap = window.setTimeout(function(){
that.time ++;
that.rest = that.time;
that.play();
},1000);
},
calculation : function(){
this.calculeHours();
this.calculeMinutes();
this.calculeSeconds();
},
calculeHours : function(){
var h = (60 * 60);
if(this.time >= h){
this.rest = (this.time % h);
this.hours = (this.time - this.rest) / h;
}else{
this.hours = 0;
}
this.h.html(this.pad(this.hours,2));
},
calculeMinutes : function(){
var m = (60);
var t = this.rest;
if(t >= m){
this.rest = (t % m);
this.minutes = (t - this.rest) / m;
}else{
this.minutes = 0;
}
this.m.html(this.pad(this.minutes,2));
},
calculeSeconds : function(){
this.seconds = this.rest;
this.s.html(this.pad(this.seconds,2));
},
pad : function(str, max) {
str = str.toString();
return str.length < max ? this.pad("0" + str, max) : str;
}
}
TimeCount.singleton = null;
TimeCount.create = function(selector,time){
if(TimeCount.singleton == null){
TimeCount.singleton = new TimeCount(selector,time);
TimeCount.singleton.play();
}else{
TimeCount.singleton.time = time;
TimeCount.singleton.rest = time;
}
}
TimeCount.end = function(){
if(TimeCount.singleton != null){
window.clearTimeout(TimeCount.singleton.ap);
TimeCount.singleton.calculation();
delete(TimeCount.singleton);
TimeCount.singleton = null;
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment