Code source
function TimerEngine(end_date,callback){
var _end_date=Object.prototype.toString.call(end_date)==='[object Date]'?end_date:new Date();
var _callback=Object.prototype.toString.call(callback)==='[object Function]'?callback:null;
var _scope=this;
var _interval=1000;
var _interval_id;
function pad(input,limit){
var input=input+'';
var limit=typeof limit=='number'?limit:1;
return input.length>=limit?input:new Array(limit-input.length+1).join('0')+input;
}
function calculate(){
var difference=_end_date.getTime()-new Date().getTime();
var data={
days:{
num:difference/(1000*60*60*24),
pad:0
},
hours:{
num:(difference/(1000*60*60))%24,
pad:0
},
minutes:{
num:((difference/1000)/60)%60,
pad:0
},
seconds:{
num:(difference/1000)%60,
pad:0
}
}
for(var i in data){
data[i].num=Math.max(Math.floor(data[i].num),0);
data[i].pad=pad(data[i].num,2);
}
data.completed=data.days.num==0&&data.hours.num==0&&data.minutes.num==0&&data.seconds.num==0;
if(_callback!=null)void _callback(data);
if(data.completed)void _scope.stop();
};
this.start=function(){
void _scope.stop();
_interval_id=setInterval(calculate,_interval);
void calculate();
};
this.stop=function(){
void clearInterval(_interval_id);
};
};
Utilisation