Having trouble with a countdown script and encountering multiple issues.
- The script does not run smoothly
- Difficult to make it repeat (closure)
- Struggling with delaying the start and repeat (closure)
Seeking assistance in fixing this code which should ideally work but is not functioning correctly.
I require the following functionality:
a. The counter starts after a delay number of seconds once the page loads,
b. When the counter reaches 0, it restarts after another delay number of seconds
Specific Issues:
- Counter seems to wait an extra second before counting down
- No pause functionality
- Repeat starts after the counter has already been running
.
// For a more accurate timer - reference: 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)
}