Question

I'm trying to figure out how to add more time to a countdown timer each time a button/link is clicked. I found a piece of code that works, but I don't know how I can edit this code to add more time to the countdown.

In my HTML, I have a div with and id of "timerDiv" and that's where the timer shows up on my page.

Here is the code:

window.onload = function() {
/*  set your parameters(
number to countdown from, 
pause between counts in milliseconds, 
function to execute when finished
) 
*/
startCountDown(100, 1000, whenTimerEnds);
}

function startCountDown(i, p, f) {
//  store parameters
var pause = p;
var fn = f;

//  make reference to div
var countDownObj = document.getElementById("timerDiv");
if (countDownObj == null) {

//  error
alert("div not found, check your id");

//  bail
return;
}
countDownObj.count = function(i) {

//  write out count
this.innerHTML = i;
if (i == 0) {

//  execute function
fn();

//  stop
return;
}
setTimeout(function() {

//  repeat
countDownObj.count(i - 1);
},
pause
);
}

//  set it going
countDownObj.count(i);
}

function whenTimerEnds() {
alert("hi alex");
}
Was it helpful?

Solution

Here's another code for your countdown:

timeout = null;
time = null;
startCountdown(5, 1000, end);

// To add time
$('#add').on('click', function(){
    time = time+5;
    startCountdown(time, 1000, end);
});

function startCountdown(timen, pause, callback) {
    time = timen;
    $('#timerdiv').html(timen);
    if(timen == 0)
        callback();
    else
    {
        clearTimeout(timeout);
        timeout = setTimeout(function(){
            startCountdown(timen-1, pause, callback)
        }, pause);
    }
}

function end() {
   alert();
}

http://jsfiddle.net/Lb4dK/2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top