Skip to content

Instantly share code, notes, and snippets.

@AstDerek
Last active December 14, 2015 03:39
Show Gist options
  • Select an option

  • Save AstDerek/5022576 to your computer and use it in GitHub Desktop.

Select an option

Save AstDerek/5022576 to your computer and use it in GitHub Desktop.
(function($){
function time_to_hms (time) {
var amounts = {
hours: 60*60,
minutes: 60,
seconds: 1
},
hms = [],
unit = '',
amount = '',
scale = 1;
for (unit in amounts) {
scale = amounts[unit];
amount = Math.floor(time/scale);
time -= amount*scale;
hms.push(amount.toString().replace(/^(\d)$/,'0$1'));
}
return hms.join(':');
}
function hms_to_time (hms) {
var values;
if (hms.match(/\d+:\d+:\d+/)) {
values = hms.replace(/[\s\S]*?(\d+:\d+:\d+)[\s\S]*/,'$1').split(':');
return (parseInt(values[0])*60 + parseInt(values[1]))*60 + parseInt(values[2]);
}
if (hms.match(/\d+:\d+/)) {
values = hms.replace(/[\s\S]*?(\d+:\d+)[\s\S]*/,'$1').split(':');
return parseInt(values[0])*60 + parseInt(values[1]);
}
if (hms.match(/\d+/)) {
return parseInt(hms.replace(/[\s\S]*?(\d+)[\s\S]*/,'$1'));
}
return 0;
}
var methods = {
init: function (options) {
return this.each(function(){
var $this = $(this),
settings = {
time: false,
tick: 1,
start: function(target,settings){
return settings;
},
update: function(target,settings,remaining){},
done: function(target,settings){}
},
modified;
if (options) {
$.extend(settings, options);
}
modified = settings.start($this,settings);
settings = modified || settings;
if (settings.time === false) {
settings.time = hms_to_time($this.text());
}
settings.limit = Math.floor((new Date()).getTime()/1000) + settings.time;
settings.step = function(){
var remaining = settings.limit - Math.floor((new Date()).getTime()/1000);
remaining = remaining <= 0 ? 0 : remaining;
$this.text(time_to_hms(remaining));
settings.update($this,settings,remaining);
if (!remaining) {
clearInterval(settings.interval);
settings.done($this,settings);
}
};
settings.interval = setInterval(settings.step,Math.floor(settings.tick*1000 - 5));
settings.step();
});
}
};
$.fn.countdown = function (method) {
if (methods[method]) {
return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
}
else if (typeof method === 'object' || ! method) {
return methods.init.apply(this,arguments);
}
else {
$.error('Method ' + method + ' does not exist on jQuery.countdown');
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment