我如何在nodeJS上扩展setTimeout

时间:2016-04-12 04:41:23

标签: node.js settimeout

我想在按下按钮后1分钟关闭计算机,如果再次按下按钮,它会在上次按下后关闭。

for(var i=1; i<=10; ++i){
 setDelay();
}

var nn;
function setDelay(){
 clearTimeout(nn);
 nn = setTimeout(function(){
   console.log("shutdown");
 }, 60000);
}

但是我的代码还有另一个&#34; setTimeout&#34;太。它会正常工作吗?还是会损坏我的其他setTimeout?

1 个答案:

答案 0 :(得分:3)

我建议您创建一个允许您为其添加时间的对象:

.container {
  position: relative;
  width: 500px;
  height: 500px;
  border: 3px solid green;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
}

然后,您可以像这样使用它:

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);
    }
}