Code: Select all
Timer = function( seconds, method )
{
this.domElement = ( document != undefined ? document.createElement('span') : null );
this.secondsStart = ( seconds != undefined ? seconds : 0 );
this.method = ( method == undefined ? false : true );
this.init();
return this;
}
Timer.prototype = {
constructor : Timer,
days : 0,
hours : 0,
minutes : 0,
seconds : 0,
calcDays : false,
calcHours : false,
calcMinutes : true,
calcSeconds : true,
daysPoint : ' days ',
hoursPoint : ' hours ',
minutesPoint : ':',
secondsPoint : '',
secondsStart : 0,
secondsPast : 0,
interval : null,
domElement : null,
append : function(elem)
{
if( document == undefined ) return false;
document.body.appendChild(this.domElement);
},
enableDays : function(bool)
{
this.calcDays = ( bool == undefined ? true : false ); return this;
},
enableHours : function(bool)
{
this.calcHours = ( bool == undefined ? true : false ); return this;
},
enableMinutes : function(bool)
{
this.calcMinutes = ( bool == undefined ? true : false ); return this;
},
enableSeconds : function(bool)
{
this.calcSeconds = ( bool == undefined ? true : false ); return this;
},
format : function()
{
return ( this.days > 0 ? this.days + this.daysPoint : '' ) +
( this.hours > 0 ? this.hours + this.hoursPoint : '' ) +
( this.minutes > 0 ? this.minutes + this.minutesPoint : '' ) +
( this.seconds < 10 ? '0' + this.seconds : this.seconds );
},
calculate : function()
{
if( this.method == false )
{
this.seconds = this.secondsStart - this.secondsPast;
}
else
{
this.seconds = this.secondsStart + this.secondsPast;
}
if( this.seconds > 0 )
{
if( this.calcDays )
{
this.days = Math.floor(this.seconds / 86400);
this.seconds -= this.days*86400;
}
if( this.calcHours )
{
this.hours = Math.floor(this.seconds / 3600);
this.seconds -= this.hours*3600;
}
if( this.calcMinutes )
{
this.minutes = Math.floor(this.seconds/60);
}
if( this.calcSeconds )
{
this.seconds = this.seconds - this.minutes * 60;
}
}
else
{
this.days = 0;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
}
},
loop : function()
{
this.secondsPast++;
this.calculate();
if( this.method == false && this.seconds == 0 )
{
window.location.reload();
return;
}
if( this.domElement == undefined ) return;
this.domElement.innerHTML = this.format();
},
init : function()
{
var _this = this;
setInterval( function() { _this.loop() }, 1000 )
}
}