【问题标题】:how to cleartimeout in node.js如何在 node.js 中清除超时
【发布时间】:2011-06-18 07:44:05
【问题描述】:

您好,我们正在 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);
      }
};

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

【问题讨论】:

    标签: node.js settimeout socket.io


    【解决方案1】:

    看起来您没有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);
          }
       };
    })();
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 2011-07-19
      • 2019-04-22
      相关资源
      最近更新 更多