How to clean up in node.js

Hey. We are developing an application in node.js, socket.io and redis.

we have the following 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 cancels the timer, it does not cancel when another command is executed, what should I do to cancel the timer?

+6
source share
1 answer

It looks like you don't have break statements that will cause problems (when you try to clear the timer, it will make a new timer and clear it, but the old one will work). Perhaps this is a typo.

The main problem is that you save the timer β€œlink” in a local variable. It must be either closed or global, otherwise, when you execute the function to clear the variable, timerknock lost its value and will try clearTimeout(undefined) , which, of course, is useless. I suggest a simple close:

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

Remember that this is also a very simplified approach, and if you set a timer before the current one finishes executing, you will lose the link to this timer. This may not be a problem for you, although you can try to implement it a little differently with an object / array of timer references.

+10
source

Source: https://habr.com/ru/post/890810/


All Articles