Node.js 如何在nodeJS上扩展setTimeout
我想在按下按钮1分钟后关闭我的电脑,如果我再次按下按钮,它将在上次按下后关闭Node.js 如何在nodeJS上扩展setTimeout,node.js,settimeout,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); } for(var i=1;i我建议您创建一个允许您为其添加时间的对象: function Ti
for(var i=1; i<=10; ++i){
setDelay();
}
var nn;
function setDelay(){
clearTimeout(nn);
nn = setTimeout(function(){
console.log("shutdown");
}, 60000);
}
for(var i=1;i我建议您创建一个允许您为其添加时间的对象:
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);
为什么要在循环中调用setDelay()
?这毫无意义。setTimeout()
不会阻塞。它设置计时器并立即返回。只需确保它只运行一次。那么为什么要调用它10次呢?当你说你的代码有另一个“setTimeout”时,我想将它延长到每次调用“setDelay”1分钟-您的意思是在其他地方调用它,还是定义了一个名为“setTimeout”的新函数?我试图运行您的代码,但它说,TypeError:this.fn不是function@ToszTemsong-我修复了一个可能导致该错误的错误。