实现这一点的一种方法是使用一种看起来很像 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/