Hoang Nam
Hoang Nam

Reputation: 83

How to handle asynchronous in Javascript?

Asynchronous in Socket.io

I use 2 variables online (to count the number of online people currently) and total variable (count the total number of people visited). The problem is that when I reload page continuously online variable has not decreased, it has increased.

io.on('connection', function(sock) {

    sock.on('disconnect', function() {
        sock.broadcast.emit('Client-disconnect', --online);
    })
    io.sockets.emit('Client-connection',{ onl: ++online, tol: ++total });
}

Upvotes: 0

Views: 73

Answers (1)

smokedice
smokedice

Reputation: 1020

The connections are being left open as they are not closed when the page is either refreshed or closed. Listen to the page events to be able to close the connection before the page is removed:

window.onbeforeunload = function(e) { sock.disconnect(); };

Upvotes: 1

Related Questions