如何减少setTimeOut中的“当前”时间?

时间:2012-07-11 12:39:29

标签: javascript

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

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

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

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

2 个答案:

答案 0 :(得分: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 demo http://jsfiddle.net/JgzZQ/2/

答案 1 :(得分: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/