Timeout 很容易找到解决方案,但 Interval 有点棘手。
我想出了以下两个类来解决这个问题:
function PauseableTimeout(func, delay){
this.func = func;
var _now = new Date().getTime();
this.triggerTime = _now + delay;
this.t = window.setTimeout(this.func,delay);
this.paused_timeLeft = 0;
this.getTimeLeft = function(){
var now = new Date();
return this.triggerTime - now;
}
this.pause = function(){
this.paused_timeLeft = this.getTimeLeft();
window.clearTimeout(this.t);
this.t = null;
}
this.resume = function(){
if (this.t == null){
this.t = window.setTimeout(this.func, this.paused_timeLeft);
}
}
this.clearTimeout = function(){ window.clearTimeout(this.t);}
}
function PauseableInterval(func, delay){
this.func = func;
this.delay = delay;
this.triggerSetAt = new Date().getTime();
this.triggerTime = this.triggerSetAt + this.delay;
this.i = window.setInterval(this.func, this.delay);
this.t_restart = null;
this.paused_timeLeft = 0;
this.getTimeLeft = function(){
var now = new Date();
return this.delay - ((now - this.triggerSetAt) % this.delay);
}
this.pause = function(){
this.paused_timeLeft = this.getTimeLeft();
window.clearInterval(this.i);
this.i = null;
}
this.restart = function(sender){
sender.i = window.setInterval(sender.func, sender.delay);
}
this.resume = function(){
if (this.i == null){
this.i = window.setTimeout(this.restart, this.paused_timeLeft, this);
}
}
this.clearInterval = function(){ window.clearInterval(this.i);}
}
这些可以这样实现:
var pt_hey = new PauseableTimeout(function(){
alert("hello");
}, 2000);
window.setTimeout(function(){
pt_hey.pause();
}, 1000);
window.setTimeout("pt_hey.start()", 2000);
此示例将设置一个可暂停的超时 (pt_hey),它计划在两秒后发出“嘿”警报。另一个超时在一秒钟后暂停 pt_hey。第三个超时在两秒后恢复 pt_hey。 pt_hey 运行一秒钟,暂停一秒钟,然后恢复运行。 pt_hey 三秒后触发。
现在是更棘手的间隔
var pi_hey = new PauseableInterval(function(){
console.log("hello world");
}, 2000);
window.setTimeout("pi_hey.pause()", 5000);
window.setTimeout("pi_hey.resume()", 6000);
这个例子设置了一个可暂停的间隔(pi_hey),每两秒在控制台中写入“hello world”。五秒后超时暂停 pi_hey。另一个超时将在 6 秒后恢复 pi_hey。所以pi_hey会触发两次,运行一秒,暂停一秒,运行一秒,然后每2秒继续触发一次。
其他功能
-
clearTimeout() 和 clearInterval()
pt_hey.clearTimeout(); 和 pi_hey.clearInterval(); 是清除超时和间隔的简单方法。
-
getTimeLeft()
pt_hey.getTimeLeft(); 和 pi_hey.getTimeLeft(); 将返回多少毫秒,直到安排下一个触发器发生。