Node.js (Socket.io) - I dont want to run disconnect if user is switching page

Currently whenever a user switches a page this code block is run immediatley:

// when the user disconnects.. perform this
socket.on('disconnect', function(){
    delete SiteRooms[socket.username];
    io.sockets.emit('updateusers', usernames);
    io.sockets.emit('updateroomusers', SiteRooms);
});

I do not want to run this if the user is only switching page on my site, is there some way i can do this?

I was thinking of a timer, maybe set it to 50 sec - maybe set it to 30 sec, if not present at the time: then disconnect. But i have no idea if this is a good solution nor how to write the actual code for it..

Any ideas?

The event firing is correct. When a user switches pages, the whole execution context of that page ends, and any scripts are stopped. This includes the client code for Socket.IO.

You have a couple choices. One choice is to load your page content with AJAX. This isn't always ideal... it depends on what your site does and how it is built.

Another option is to build in that delay yourself. Wherever you keep your user data, just add a property to that object that holds a timeout for however many seconds you'd like. If the user reconnects, clear the timeout before it fires.

You can change the link by a script that changes the page content instead. I'm not to experienced, but I think JADE helps to do things like that. You have some examples at github:

https://github.com/visionmedia/jade

I think replacing blocks could be a solution for you.