我如何在nodeJS上扩展setTimeout

我想在按下button1分钟后closures电脑,如果再次按下button,它会在上次按下后closures。

for(var i=1; i<=10; ++i){ setDelay(); } var nn; function setDelay(){ clearTimeout(nn); nn = setTimeout(function(){ console.log("shutdown"); }, 60000); } 

但是我的代码也有另一个“setTimeout”。 它会正常工作吗?还是会损害我的其他setTimeout?

我build议你创build一个对象,允许你添加时间:

 function Timer(t, fn) { this.fn = fn; this.time = Date.now() + t; this.updateTimer(); } Timer.prototype.addTime = function(t) { this.time += t; this.updateTimer(); } Timer.prototype.stop = function() { if (this.timer) { clearTimeout(this.timer); this.timer = null; } } Timer.prototype.updateTimer = function() { var self = this; this.stop(); var delta = this.time - Date.now(); if (delta > 0) { this.timer = setTimeout(function() { self.timer = null; self.fn(); }, delta); } } 

那么,你可以像这样使用它:

 var timer = new Timer(60000, function() { console.log("shutdown"); }); // add one second of time timer.addTime(1000); // add one minute of time timer.addTime(1000 * 60);