必要なのは単純なタイマーだけです。多くの種類があります。これは、クラスとしてうまく抽象化した安価な例です。.reset()を呼び出すことにより、タイマーを「続行」できます。
function Timeout(seconds, callback){
this.length = seconds * 1000;
this.callback = callback;
this.start();
}
Timeout.prototype = {
start: function(){
var self = this;
this.stop();
this.timer = setTimeout(function(){
self.complete();
},this.length);
},
stop: function(){
if (this.timer) clearTimeout(this.timer);
this.timer = null;
},
complete: function(){
if (this.callback) this.callback();
this.stop();
},
reset: function() {
this.stop();
this.start();
}
}
新しいタイマーを開始します。
var timer = new Timeout(3 * 60, logout);
timer.reset(); // refresh the timer
timer.stop(); // cancel the timer