G.Thompson
G.Thompson

Reputation: 827

Logical socket.io understanding; connections and variables

to many this may be an easy question but I'm trying to figure out the reason/logistics as to how socketIO handles variables. In the following code, x is set to 0, every second it counts up. Now if you had 1000 clients connected, every time the connect would each client get a new count starting at 0 and not affect every other connected client?

Also, is there a way to emit a new number to ever connected client instead of each connected client? Thanks!

io.sockets.on('connection', function (socket) {
    x= 0;
    var socketSend = setInterval(function(){
        x = x+1;
        socket.emit('count', { number: x });
    }, 1000);

});

Upvotes: 0

Views: 88

Answers (1)

Gntem
Gntem

Reputation: 7155

the socketSend is visible only to inside the callback of connection event, so every time a client connects the callback is called, passing along the socket object, so every client will get 0 as a start and the count will begin.

Upvotes: 1

Related Questions