0

I would finally like to reach some clarity on this aspect of programming, being basically self-taught. It's to do with passing variables around between functions.

With the code below, data.roomId is not recognized in the first function (obviously). I could place the function inside the joinRoom function to make it recognize data.roomId, but then how does the leaveRoom function recognize sendHeartbeat?

`io.on('connection', function (socket) {
    function sendHeartbeat(){
        setTimeout(sendHeartbeat, 8000);
        socket.broadcast.to(data.roomId).emit('ping', { beat : 1 });
    }
    socket.on('joinRoom', function (data) {
        socket.join(data.roomId)
        setTimeout(sendHeartbeat, 8000);
    });
    socket.on('leaveRoom', function (data) {
        socket.leave(data.roomId)
        clearTimeout(sendHeartbeat)
    });
});`
1
  • sendHeartbeat is defined within the scope of function(callback) - so it is in scope, therefore (as you put it) "recognized" Commented Sep 21, 2017 at 23:39

1 Answer 1

1

You can do what we call a closure, it is a function that returns a function keeping track of local variables. It is a cool concept !

function sendHeartbeat(roomId){
    return function() {
        socket.broadcast.to(roomId).emit('ping', { beat : 1 });
    }
}
socket.on('joinRoom', function (data) {
    socket.join(data.roomId)
    setTimeout(sendHeartbeat(data.roomId), 8000);
});

You call the function sendHeartbeat passing it the roomId, and it returns the function you want to be executed in your setTimeout :)

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, good to know! Guess I'll test it in future but right now I've moved away from pinging to keep a socket.io connection open and went with setting session cookies using npmjs.com/package/express-socket.io-session

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.