Angry B
Angry B

Reputation: 305

How to stop server-side timer on user disconnect? (node.js/socket.io)

I have some server-side timer, that worked on socket.io:

// timer function
    function startTimer() {
         var countdown = 15000;
         var serverInterval = setInterval(function () {
            countdown -= 1000;
            socket.in(room_name).emit('timer', {countdown: countdown});
         }, 1000);
     }

// timer usage      
     socket.on("start timer", function() {
         startTimer()
     }

But when user disconnecting, I want to clearInterval and stop that timer:

socket.on('disconnect', function() {
      clearInterval(serverInterval);
});

What causes the error "serverInterval is not defined".

How to make variable global in current document, but not global in whole project and stop my server-side timer on user disconnect?

Upvotes: 1

Views: 762

Answers (2)

Javier Rey
Javier Rey

Reputation: 1620

Make the variable global by defining it in the global scope, instead of var serverInterval = ... should be global.serverInterval = ....

Or, better, attach the variable to the socket object: socket.serverInterval = ..., and in the disconnection: clearInterval(socket.serverInterval).

Upvotes: -1

marvel308
marvel308

Reputation: 10458

You can use a function to store the context of serverInterval like

var ServerInterval = (function () {
    var serverInterval;
    return {
            set: function (obj) {
            serverInterval = obj;
            },
            get : function() {
                return serverInterval;
            }
    };

})();

// timer function
    function startTimer() {
         var countdown = 15000;
         ServerInterval.set(setInterval(function () {
            countdown -= 1000;
            socket.in(room_name).emit('timer', {countdown: countdown});
         }, 1000));
     }

// timer usage      
     socket.on("start timer", function() {
         startTimer()
     }

socket.on('disconnect', function() {
      clearInterval(ServerInterval.get());
});

and then call it using a getter/ setter

Upvotes: 2

Related Questions