如何减少 setTimeOut 中的“当前”时间?例如,我有一个从 100 秒开始的倒计时,40 秒后(因此在 60 秒)我单击一个按钮,它会立即减少到 50 秒(-10 秒)。
下面示例中的链接将在 100 秒后启用。基本上,我正在寻找一种方法,可以在每次按下按钮时从倒计时(当前位置)减少 10 秒。
function enableLink() {
setTimeout('enableAnchor( "anchor0", "mylink.php" )', 100000);
}
如果这是不可能的,是否有任何语言或库(也许是 JQuery 或 AJAX?)可以让我做到这一点?
最佳答案
不要将计时器值用于任何实际逻辑,而是手动完成:
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/
关于javascript - 如何减少setTimeOut中 'current'的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11432868/