0

如何减少 setTimeOut 中的“当前”时间?例如,我从 100 秒开始倒计时,40 秒后(所以在 60 秒)我单击一个按钮,它立即减少到 50 秒(-10 秒)。

下面示例中的链接在 100 秒后启用。基本上,我正在寻找一种方法来减少每次按下按钮时(当前位置)倒计时的 10 秒。

function enableLink() {
    setTimeout('enableAnchor( "anchor0", "mylink.php" )', 100000);
}

如果这不可能,是否有任何语言或库(也许是 JQuery 或 AJAX?)可以让我这样做?

4

2 回答 2

3

不要将计时器值用于任何实际逻辑,请手动执行:

var msLeft = 100000,
    prev = new Date();

     //This timer is simply polling how much time has passed using accurate methods and reduces it accordingly from msLeft 
var timerId = window.setInterval( function() {
    var cur = new Date(),
        progress = cur - prev;

    prev = cur;
    msLeft -= progress;

    if( msLeft <= 0 ) {
        window.clearInterval(timerId);
        counteddown();
    }
}, 50 ); 

document.onclick = function() {
    msLeft -= 10000; //Each click reduces 10 seconds from the countdown
};

document.onkeyup = function() {
    msLeft += 10000; //Each keyup adds 10 seconds to the countdown
};

jsfiddle 演示http://jsfiddle.net/JgzZQ/2/

于 2012-07-11T12:50:16.500 回答
0

实现这一点的一种方法是使用一种看起来很像 setTimeout 的方法,但返回一个对象,该对象的方法允许您减少时间。这消除了继续轮询以查看时间是否减少的需要,仅在必要时重新分配计时器:

function adjustableTimer(action, initialMs){   
    return {
        timerId: setTimeout(action, initialMs),
        startTime: new Date(),
        initialMs: initialMs,
        action: action,
        reduce: function(howMuch){
            var elapsedTime = new Date() - this.startTime;
            var remainingTime = this.initialMs - elapsedTime;
            var newTime = remainingTime - howMuch;
            clearTimeout(this.timerId);            
            this.timerId = setTimeout(this.action,newTime);
        }
    };       
}

用法:

var timer = adjustableTimer(function(){ alert("Im finished"); }, 10000); // initially 10 seconds
// when wanting to reduce:
timer.reduce(1000); // reduce timer by 1 second

现场示例:http: //jsfiddle.net/gKjEt/

于 2012-07-11T13:10:32.557 回答