Socket.io: How can I check to see if a certain number of clients have emitted an event?

With Socket.io, I'm querying all connected clients to get a status on whether or not they are ready to do something. Once they have all responded back, I want to emit an event.

How can I check whether or not each client has responded, assuming that I already know how many clients are connected?

Right now, the code looks like this:

var totalClients = 2; //countClientSockets();
var readyClients = 0;

socket.on("syncReady", function() {
        debug.log("Client is ready!");
        readyClients++;
        debug.log("Ready Clients: " + readyClients + "/" + totalClients.length);
        if (readyClients == totalClients.length) {
            debug.log("Room is synced! Sending start event...");
            io.sockets.emit("play");
        } else {
            debug.log("Room is not synced yet! Waiting...");
        }
    });

However, this results in the console output (after both clients have gotten ready and responded):

[Debug][Handler]: Client is ready!
[Debug][Handler]: Ready Clients: 1/2
[Debug][Handler]: Room is not synced yet! Waiting...
[Debug][Handler]: Client is ready!
[Debug][Handler]: Ready Clients: 1/2
[Debug][Handler]: Room is not synced yet! Waiting...

I would like it to output:

[Debug][Handler]: Client is ready!
[Debug][Handler]: Ready Clients: 1/2
[Debug][Handler]: Room is not synced yet! Waiting...
[Debug][Handler]: Client is ready!
[Debug][Handler]: Ready Clients: 2/2
[Debug][Handler]: Room is synced! Sending play event...

What would be a better way to do this?

You definitely have the right idea and your code is close to correct.

I'm guessing the main issue is that your readyClients is defined inside your io.on('connection',function(){}) handler (not totally sure though since that part of the code isn't shown).

You want to keep that variable outside of io.on so that it doesn't get recreated on every connection. I think this is what you are looking for:

var totalClients = 2;
var readyClients = 0;

io.on('connection', function (socket) {
  socket.on("syncReady", function() {
    console.log("Client is ready!");
    readyClients++;
    console.log("Ready Clients: " + readyClients + "/" + totalClients);
    if (readyClients == totalClients) {
      console.log("Room is synced! Sending start event...");
      io.sockets.emit("play");
    } else {
      console.log("Room is not synced yet! Waiting...");
    }   
  }); 
});

I also changed totalClients.length to totalClients since totalClients isn't an array.