向倒数计时器添加更多秒数

时间:2014-02-10 00:10:55

标签: jquery timer add countdown seconds

我想弄清楚每次点击一个按钮/链接时如何为倒计时器添加更多时间。我找到了一段可行的代码,但我不知道如何编辑此代码以增加倒计时的时间。

在我的HTML中,我有一个div和id为“timerDiv”的div,这就是我的页面上显示的计时器。

以下是代码:

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");
}

1 个答案:

答案 0 :(得分:0)

这是倒计时的另一个代码:

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/