Created
April 22, 2010 00:17
-
-
Save beaucollins/374626 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
var Timer = function(end, options){ | |
if(!options) options = {}; | |
if(!options['timerInterval']) options['timerInterval'] = 1; | |
if(!options['periods']) options['periods'] = { | |
'milliseconds' : 1, | |
'seconds' : 1000, | |
'minutes' : 60, | |
'hours' : 60, | |
'days' : 24, | |
'weeks' : 7 | |
} | |
if(!end) throw('End date not provided'); | |
var date = new Date(end); | |
var timer = this; | |
var timer_id; | |
var periods_in_milliseconds = []; | |
var m = 1; | |
for(period in options.periods){ | |
periods_in_milliseconds.push([period, m * options.periods[period]]); | |
m *= options.periods[period]; | |
} | |
periods_in_milliseconds = periods_in_milliseconds.reverse(); | |
this.calculate = function(){ | |
var difference = date.getTime() - (new Date()).getTime(); | |
if(difference <= 0){ | |
if(options['onComplete'], options['onComplete'](date)); | |
return; | |
} | |
var periods = {} | |
for(var i=0;i<periods_in_milliseconds.length;i++){ | |
var divisor = periods_in_milliseconds[i][1]; | |
periods[periods_in_milliseconds[i][0]] = Math.floor(difference / divisor); | |
difference %= divisor; | |
} | |
if(options['onTimer']) options['onTimer'](periods); | |
} | |
this.stop = function(){ | |
clearTimeout(timer_id); | |
} | |
this.start = function(){ | |
timer_id = setInterval(function(){ | |
timer.calculate(); | |
}, options['timerInterval']); | |
timer.calculate(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment