javascript - 如果通过套接字连接的用户数量至少为 1,则运行用户定义的函数 - Nodejs

标签 javascript node.js sockets

如果没有用户连接到套接字停止 setInterval 函数,我正在尝试找到一种方法来停止 setInterval(test,5000) 函数运行,因为它会导致很多问题浪费资源。

找到了方法,但不知道怎么写

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

下面是我的代码:

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).
}

});

如果没有用户连接,如何最好地停止执行 SetInterval(test,5000)?

最佳答案

要停止setInterval,请使用clearInterval

Refer to Stop setInterval call in JavaScript

如果您没有/超过 1 个连接的用户,您是否还需要帮助来停止/恢复 setInterval

如果是这样,您可以尝试在计数器的同时管理对 setInterval 的引用:

var connectCounter = 0;  
var interval = undefined;

然后:

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

然后:

connectCounter--;
if (connectCounter <= 0 && interval !== undefined) interval = clearInterval(interval);

关于javascript - 如果通过套接字连接的用户数量至少为 1,则运行用户定义的函数 - Nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510472/

相关文章:

javascript - ReactJS 中的 PayFast 支付集成

javascript - HTML Canvas arc 在错误的位置绘制 JavaScript

javascript - $$var(在 php 中)等同于 javascript

mysql - 使用 mysql 和 nodeJS 构建一个 docker

c - 从套接字读取缓冲区

使用原型(prototype)的 Javascript 类系统

javascript - Express 中间件中丢失 ajax 数据

node.js - 如何修复路由以在 node.js 的子文件夹中查找 View

python - IRC 机器人无法连接到服务器 - Python

c - Tcp 服务器关闭卡在 TIME_WAIT,无法再次在同一端口上打开服务器