Il Timeout è stato abbastanza facile da trovare una soluzione, ma l'intervallo è stato un po 'più complicato.
Ho ideato le seguenti due classi per risolvere questo problema:
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);}
}
Questi possono essere implementati come tali:
var pt_hey = new PauseableTimeout(function(){
alert("hello");
}, 2000);
window.setTimeout(function(){
pt_hey.pause();
}, 1000);
window.setTimeout("pt_hey.start()", 2000);
Questo esempio imposterà un Timeout sospendibile (pt_hey) che è programmato per avvisare, "hey" dopo due secondi. Un altro timeout mette in pausa pt_hey dopo un secondo. Un terzo Timeout riprende pt_hey dopo due secondi. pt_hey corre per un secondo, si ferma per un secondo, quindi riprende a correre. pt_hey si attiva dopo tre secondi.
Ora per gli intervalli più complicati
var pi_hey = new PauseableInterval(function(){
console.log("hello world");
}, 2000);
window.setTimeout("pi_hey.pause()", 5000);
window.setTimeout("pi_hey.resume()", 6000);
Questo esempio imposta un intervallo di pausa (pi_hey) per scrivere "hello world" nella console ogni due secondi. Un timeout mette in pausa pi_hey dopo cinque secondi. Un altro timeout riprende pi_hey dopo sei secondi. Quindi pi_hey si attiverà due volte, correrà per un secondo, si fermerà per un secondo, correrà per un secondo e poi continuerà ad attivarsi ogni 2 secondi.
ALTRE FUNZIONI
clearTimeout () e clearInterval ()
pt_hey.clearTimeout();
e pi_hey.clearInterval();
serve come un modo semplice per cancellare i timeout e gli intervalli.
getTimeLeft ()
pt_hey.getTimeLeft();
e pi_hey.getTimeLeft();
restituirà quanti millisecondi devono trascorrere prima che si verifichi il trigger successivo.