How to timeout your Socket.io Client Listener

Hi!

[Versão em Português]

So I have bumped into an issue with the socket.io-client module where you cannot timeout listeners, so if for example you did this in your code:


 socket_client.on("my_event",(response)=>{
   
    console.log("Event responded");
   
});

There are no properties you can pass (As far as I have looked into it, I know there are open issues about this though) to timeout this listener, so if you have a long time client connected it will experience an increase of memory, this is not a memory leak though, the objects are actually there waiting to get into action, but there could be a situation where an error ocurred and your listener will stay there forever until you stop the process.

So to mitigate this you could add to your code this very simple function:


var addListener = (socket_client, eventName, 
                  callback, timeout)=>{

    // Adding the event listener as
    //you would normally do

    socket_client.on(eventName,callback);

    // If the listener is not cleaned yet
    //after timeout, this will do the trick

    setTimeout(()=>{

      if(socket_client.hasListeners(eventName)){

        socket_client.removeListener(eventName, callback);

        console.log(eventName + " listener was cleaned");

      }

    }, timeout);

  }

Thank you.

Advertisements

One thought on “How to timeout your Socket.io Client Listener”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s