R
R
Roman Korolyov2019-01-31 11:54:24
Node.js
Roman Korolyov, 2019-01-31 11:54:24

Function is executed multiple times, why ( Node JS + Socket IO )?

Friends, hello. Faced such problem that sockets send function several times at the same time.
It is necessary to make it so that it goes 1 time in 3 seconds. Maybe the problem is in setTimeout? ( usersCount() function )
Code example:

io.sockets.on('connection', function(socket){
    console.log('connect');
   setTimeout(usersCount, 3000);
   
});

/* Доступ к статистике */ 

function usersCount() {
    connection.query('SELECT COUNT(*) FROM `users`', function(err, rows) {
    users = rows['0']['COUNT(*)'];
    });  
    
    https_server.getConnections(function (err, count) {
    online = count;
    });
    
    connection.query('SELECT COUNT(*) FROM `drops`', function(err, rows) {
    drops_count = rows['0']['COUNT(*)'];
    });


      var json = {
      
      users: users,
      online: online,
      drops: drops_count
      
      };

        socket.emit('stats',json); // отправим в сокеты

   setTimeout(usersCount, 5*3000);
}

5c52b7a5ab40c578145325.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Korolyov, 2019-01-31
@VitteDev

Figured it out, removed
io.sockets.on('connection', function(socket){

K
Kirill Kudryavtsev, 2019-01-31
@Deissh

With SetTimeout you don't limit the number of executions per second, you just delay the call by 3 seconds. And if there were 2 connections in a row, then after 3 seconds usersCount will be called 2 times.

V
Vladimir Skibin, 2019-01-31
@megafax

You need to perform the send function only if there are connected users and send across all connections (they can be further divided into rooms/groups and send the necessary data for each room).

setIterval(usersCount, 5 * 3000);

function usersCount() {
  io.sockets.clients((err, clients) => {
    if (err) throw err;
    if (clients.length) {
     // do some sql
     io.sockets.emit('stats', json);
    }
  });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question