嗨,我们正在 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 已经失去了它的值并且会尝试 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);
      }
   };
})();

请注意,这也是一种非常简单的方法,如果您在当前计时器完成执行之前设置了一个计时器,那么您将失去对该计时器的引用。这对您来说可能不是问题,尽管您可能会尝试以稍微不同的方式实现它,使用计时器引用的对象/数组。

关于node.js - 如何在 node.js 中清除超时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6394618/

10-14 18:47
查看更多