如何在node.js中cleartimeout

XMe*_*Men 9 settimeout node.js 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 statement 
            timerknock=setTimeout(function() {
                //some  statemetn
            },20*1000);
        case 'other command ':
            // some statement    
            clearTimeout(timerknock);
      }
};
Run Code Online (Sandbox Code Playgroud)

但当它取消定时器时,当其他命令执行时它没有被取消,我该怎么办才能取消定时器?

dav*_*vin 11

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

您的主要问题是您将计时器"reference"存储在局部变量中.这需要是封闭的或全局的,否则当你执行清除变量的函数时,它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);
      }
   };
})();
Run Code Online (Sandbox Code Playgroud)

请注意,这也是一种非常简单的方法,如果在当前的计时器完成执行之前设置计时器,则会丢失对该计时器的引用.这对您来说可能不是问题,尽管您可能尝试使用定时器引用的对象/数组稍微改变一下.