开发者

how to cleartimeout in node.js

Hi We are developing application in node.js , socket.io , and 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 ?


Looks like you don't have break statements, 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.

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, timerknock has lost its value and will try and clearTimeout(undefined) which is of course, useless. I suggest a simple closure:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜