Несколько часов назад я закончил разработку таймера JavaScript.
Это должно сделать свое дело.
function miniTimer(s,callback,opt){
function getParam(value,defaultValue){
return typeof value == 'undefined' ? defaultValue : value;
}
this.s = getParam(s,0);
this.callback = getParam(callback,null);// a callback function that takes the current time in seconds as the first parameter and the formated time as the second
var opt = getParam(opt,{});
this.settings = {
masterCallback : getParam(opt.masterCallback,null),// same as above, but this one is called when the miniTimer finishes it's work (if maxPaceDuration or limitValue is set)
autoplay : getParam(opt.autoplay,false),
limitValue : getParam(opt.limitValue,null),
maxPaceCount : getParam(opt.maxPaceCount,null),
paceDuration : getParam(opt.paceDuration,1000),//milisec,
paceValue : getParam(opt.paceValue,1)//increment with only one second; set to -1 to countdown
};
this.interval = 0;
this.paceCount = 0;
if(this.settings.autoplay)
this.start();
return this;
}
miniTimer.prototype = {
toString : function(){
var d = Math.floor(this.s / (24 * 3600));
var h = Math.floor((this.s - d* 24 * 3600) / 3600);
var m = Math.floor((this.s - d* 24 * 3600 - h * 3600) / 60);
var s = this.s % 60;
if(h <= 9 && h >= 0)
h = "0"+h;
if(m <= 9 && m >= 0)
m = "0"+m;
if(s <= 9 && s >= 0)
s = "0"+s;
var day = d != 1 ? "days" : "day";
return d+" "+day+" "+h+":"+m+":"+s;
},
nextPace : function(){
if((this.settings.maxPaceCount != null && this.settings.maxPaceCount <= this.paceCount)
|| (this.settings.limitValue != null && this.settings.limitValue == this.s))
{
this.stop();
if(this.settings.masterCallback != null)
this.settings.masterCallback(this.s,this.toString());
return;
}
this.paceCount++;
var aux = this.s + this.settings.paceValue;
this.s += this.settings.paceValue;
if(this.callback != null)
this.callback(this.s,this.toString());
return this;
},
start : function(){
var $this = this;
this.interval = setInterval(function(){$this.nextPace();},this.settings.paceDuration);
return this;
},
stop : function(){
clearInterval(this.interval);
return this;
}
}
Теперь все, что вам нужно сделать, это настроить правильную функцию обратного вызова:
var el = document.getElementById('timer');
function getNextTuesday(){
var nextTuesday = new Date();
var t = nextTuesday.getDay();
t = t > 2 ? 9 - t : 2 - t;
nextTuesday.setDate(nextTuesday.getDate() + t);
return nextTuesday;
}
var showDuration = 2 * 60 * 60;//2h
var t = new miniTimer(Math.floor((getNextTuesday() - new Date())/1000),function(date,string){
if(date > 0)
el.innerHTML = string;
else
{
if(date <= -showDuration)
t.s = Math.floor((getNextTuesday() - new Date())/1000);
el.innerHTML = "<img src='http://t2.gstatic.com/images?q=tbn:ANd9GcT3CEVtaAYQJ4ALZRmgMHsCA8CG5tdpauLqSMhB66HJP_A0EDPPXw'>";
}
},{autoplay:true,paceValue : -1});
вот рабочий пример: http://jsfiddle.net/gion_13/8wxLP/1/