I keep running into several issues when creating a countdown script
- it does not run smoothly
- hard to make it repeat (closure)
- hard to delay the start and to delay the repeat (closure)
Can someone please help me FIX this code which should work in my opinion but doesn't
the processing I need is
a. counter starts delay number of seconds after the page loads,
b. when counter reaches 0, the countdown RE-starts after delay number of seconds
Issues:
- when it starts, the counter seems to wait an additional second before counting down
- it does not pause
- the repeat starts after the counter has continued
.
// more accurate timer - https://gist.github.com/1185904
function interval(duration, fn){
this.baseline = undefined
this.run = function(){
if(this.baseline === undefined){
this.baseline = new Date().getTime()
}
fn()
var end = new Date().getTime()
this.baseline += duration
var nextTick = duration - (end - this.baseline)
if(nextTick<0){
nextTick = 0
}
(function(i){
i.timer = setTimeout(function(){
i.run(end)
}, nextTick)
}(this))
}
this.stop = function(){
clearTimeout(this.timer)
}
}
window.onload=function() {
var cnt1 = 10;
var delay1 = 5;
var timer1 = new interval(1000, function(){
document.getElementById('out1').innerHTML=cnt1--
if (cnt1 <= 0) { // trying to reset
timer1.stop(); // does not work
cnt1 = 10;
setTimeout(function() { timer1.run()},delay1*1000)
}
})
setTimeout(function() { timer1.run()},delay1*1000)
}
Object exposing
start([delay])
andstop()
.http://jsfiddle.net/RVBDQ/3/
I've rewritten your code to produce the desired results. Your previous code was very inefficient. See my script comments for usage.
Fiddle: http://jsfiddle.net/RVBDQ/1/