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?
via Murlidhar Fichadia
No comments:
Post a Comment