如何清除 node.js 中的超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6394618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to cleartimeout in node.js
提问by XMen
Hi We are developing application in node.js , socket.io , and redis.
嗨,我们正在 node.js、socket.io 和 redis 中开发应用程序。
we have this procedure :
我们有这个程序:
exports.processRequest = function (request,result) {
var self = this;
var timerknock;
switch(request._command) {
case 'some command': // user login with username
// some statement
timerknock=setTimeout(function() {
//some statemetn
},20*1000);
case 'other command ':
// some statement
clearTimeout(timerknock);
}
};
but when it cancel the timer it is not getting canceled when other command is executed , what should i do to cancel the timer ?
但是当它取消计时器时,它不会在执行其他命令时被取消,我应该怎么做才能取消计时器?
回答by davin
Looks like you don't have breakstatements, which is going to cause problems (when you try and clear the timer it will make a new timer and clear it, but the old one will still run). Maybe that's a typo.
看起来您没有break语句,这会导致问题(当您尝试清除计时器时,它将创建一个新计时器并清除它,但旧计时器仍会运行)。也许这是一个错字。
Your main problem is you're storing the timer "reference" in a local variable. That needs to be either enclosed or global, otherwise when you execute the function to clear the variable, timerknockhas lost its value and will try and clearTimeout(undefined)which is of course, useless. I suggest a simple closure:
您的主要问题是您将计时器“引用”存储在局部变量中。这需要是封闭的或全局的,否则当你执行函数来清除变量时,它timerknock已经失去了它的值并且会尝试,clearTimeout(undefined)这当然是无用的。我建议一个简单的关闭:
exports.processRequest = (function(){
var timerknock;
return function (request,result) {
var self = this;
switch(request._command) {
case 'some command': // user login with username
// some statement
timerknock=setTimeout(function() {
//some statemetn
},20*1000);
case 'other command ':
// some statement
clearTimeout(timerknock);
}
};
})();
Be aware that this too is a very simplistic approach, and if you set a timer before the current one has finished executing then you lose the reference to that timer. This might not be a problem for you, although you might try to implement this a little differently, with an object/array of timer references.
请注意,这也是一种非常简单的方法,如果您在当前计时器完成之前设置了一个计时器,那么您将失去对该计时器的引用。这对您来说可能不是问题,尽管您可能会尝试以稍微不同的方式实现它,使用计时器引用的对象/数组。

