node process can not find setTimeout object in subsequent requests

余生颓废 提交于 2019-12-24 19:39:14

问题


I am trying to clear timeout set using setTimeout method by node process, in subsequent requests (using express). So, basically, I set timeout when our live stream event starts (get notified by webhook) and aim to stop this for guest users after one hour. One hour is being calculated via setTimeout, which works fine so far. However, if event gets stopped before one hour, I need to clear the timeout. I am trying to use clearTimeOut but it just can't find same variable.

// Event starts
var setTimeoutIds              = {};    
  var val  = req.body.eventId;
  setTimeoutIds[val] =  setTimeout(function() {

        req.app.io.emit('disable_for_guest',req.body);                                
        live_events.update({event_id:req.body.eventId},{guest_visibility:false},function(err,data){
                                            //All ok
         });
     }, disable_after_milliseconds);
     console.log(setTimeoutIds);                                        
     req.app.io.emit('session_started',req.body);

When event ends:
 try{
           var event_id = req.body.eventId;
           clearTimeout(setTimeoutIds[event_id]);
           delete setTimeoutIds[event_id];
      }catch(e){
           console.log('Event ID could not be removed' + e);
      }
 req.app.io.emit('event_ended',req.body);

Output :

Output


回答1:


You are defining setTimeoutIds in the scope of the handler. You must define it at module level.

var setTimeoutIds = {};    

router.post('/webhook', function(req, res) {
     ...

That makes the variable available until the next restart of the server.

Note: this approach only works as long as you only have a single server with a single node process serving your application. Once you go multi-process and/or multi-server, you need a completely different approach.



来源:https://stackoverflow.com/questions/51301332/node-process-can-not-find-settimeout-object-in-subsequent-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!