如何在node.js中清除超时

如何在node.js中清除超时,node.js,settimeout,socket.io,Node.js,Settimeout,Socket.io,大家好,我们正在node.js、socket.io和redis中开发应用程序 我们有以下程序: exports.processRequest = function (request,result) { var self = this; var timerknock; switch(request._command) { case 'some command': // user login with username // some

大家好,我们正在node.js、socket.io和redis中开发应用程序

我们有以下程序:

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

但是当它取消计时器时,当执行其他命令时,它不会被取消,我应该如何取消计时器?

看起来您没有
break
语句,这将导致问题(当您尝试清除计时器时,它将生成一个新计时器并清除它,但旧的计时器仍将运行)。也许那是个打字错误

您的主要问题是将计时器“引用”存储在局部变量中。这需要是封闭的或全局的,否则在执行函数清除变量时,
timerknock
已丢失其值,并将尝试清除超时(未定义),这当然是无用的。我建议一个简单的结束:

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);
      }
   };
})();
请注意,这也是一种非常简单的方法,如果在当前计时器完成执行之前设置计时器,则会丢失对该计时器的引用。这对您来说可能不是问题,尽管您可能会尝试使用计时器引用的对象/数组以稍微不同的方式实现它