countdown with repeat and delay
Witht he help of Davin
by javajack
HTML
<div id="out1">This will start in 5 seconds</div>
<!-- button onclick="window.timer1.stop();return false;">stop</button>
<button onclick="window.timer1.start();return false;">start immediately</button>
<button onclick="window.timer1.start(3000);return false;">start with 3 second delay</button -->
CSS
.test1 {
color: #333333;
font: bold 18px/28px Arial, sans-serif;
}
.test2 {
color: #ff0000;
font: bold 23px/33px Arial, sans-serif;
}
.test3 {
font: italic bold 18px/28px Arial, sans-serif;
}
JavaScript
// Timer class (c) 2011 mplungjan javascripts(a)plungjan.name
// built with the help of Davin of SO, SEB. Timer based on Manast's setInterval replacement.
// the script can be externalised easily and only the settings edited by the end user
function Timer() {
function interval(duration, fn, delay){
this.timer = null;
this.duration = duration;
this.fn = fn;
this.start(delay);
}
interval.prototype.start = function(delay){
if (this.timer) {return;}
var self=this;
this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
var self = this,
nextTick = called ? this.duration - (new Date - called) : 0;
this.timer = setTimeout(function(){
self.run(new Date);
self.fn();
}, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
clearTimeout(this.timer);
this.timer = null;
};
function formatString(haystack,needle) {
return haystack.replace("$1",needle);
}
this.setTimer = function(timerobj) {
//-------------------------------
var container = $("#"+timerobj.container)
container.html(formatString(timerobj.initialMessage,timerobj.initialDelay));
var cnt = timerobj.countdownFrom;
var timer = new interval(1000, function(){
// console.log(arguments);
--cnt;
container.html(formatString(timerobj.countdownMessage,"<span class='test2'>" + ((cnt<0)?0:cnt) + "</span>" + " second"+(cnt==1?"":"s")));
if (cnt < 0) {
cnt = timerobj.countdownFrom;
container.animate({
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 1000, function() {
// Animation complete.
container.html(formatString(timerobj.restartMessage,timerobj.delay)).animate({
opacity: 1,
left: '+=50',
height: 'toggle'
}, 1000);
});
timer.stop();
timer.start(timerobj.delay*1000);
}
},...