0

I am trying to find a way to stop setInterval(test,5000) function from running if no user is connected to the socket stop setInterval function as it causes lot of waste of resources.

I found the method but I dont know how to put it

io.engine.clientsCount  //this will tell number of users connected but only inside socket.on function.

below is my code:

var connectCounter = 0;  


app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});


 function test()
  {
    httpk.get("api-url", function(res) {
        var body = ''; 
        res.on('data', function(data){
            body += data;
        });

        res.on('end', function() {
            var parsed = JSON.parse(body);
            console.log(parsed.johndoe.example1);
            nsp.emit('live-quote', parseFloat(parsed.johndoe.example1);
        });
    });
  }

     setInterval(test,5000);

nsp.on('connection', function(socket){


  //Make a http call
  connectCounter++;
  nsp.emit('live-users',connectCounter);
  console.log('1 user connected, Total Joined: '+connectCounter);

  socket.on('disconnect', function(){
    connectCounter--;
    nsp.emit('live-users',connectCounter);
    console.log('1 user disconnected, Total Left: '+connectCounter);


  });

console.log("total clients: "+io.engine.clientsCount);

if(io.engine.clientsCount >= 1)
{
  //do something
  //if I put setInterval here it will cause problems, that is for each connection it will run setInterval causing lot of http get request
  // meaning, if 100 users then 100 get request in 5 seconds (depending on setInterval time).
}

});

How do I best stop execution of SetInterval(test,5000) if no users connected?

Murlidhar Fichadia
  • 2,589
  • 6
  • 43
  • 93

1 Answers1

1

To stop setInterval, use clearInterval

Refer to Stop setInterval call in JavaScript

Do you also need help to stop/resume setInterval if you have no/1+ connected user?

If so, you can try managing a reference to your setInterval at the same time as your counter:

var connectCounter = 0;  
var interval = undefined;

then:

connectCounter++;
if (interval === undefined) interval = setInterval(test,5000);

then:

connectCounter--;
if (connectCounter <= 0 && interval !== undefined) interval = clearInterval(interval);
RaphaMex
  • 2,781
  • 1
  • 14
  • 30
  • its not about just using clearInterval. I am aware of clearInterval JS function. But here the issue is with respect to sockets. The function test and setInterval is outside the scope of nsp.on() socket connection and total number of users connected can only be found inside nsp.on() function but I cant have setInterval inside socket.on connection. As it would run setInterval for each connected client. – Murlidhar Fichadia Jun 13 '17 at 00:21
  • Okay. I will give it a try in few hrs time. – Murlidhar Fichadia Jun 13 '17 at 00:26