简体   繁体   English

Angular,socket.io和setInterval-如何管理视图更改

[英]Angular, socket.io and setInterval - how to manage the view changes

I have an angularjs based webapp which is complemented by an ExpressJS + socket.io + Node backend. 我有一个基于angularjs的webapp,由ExpressJS + socket.io + Node后端补充。 Most of the data traffic is based on REST Web Services, except for some realtime graphs. 除某些实时图形外,大多数数据流量基于REST Web服务。 The data is pushed using a setInterval when the socket.on('connection') is established. 建立socket.on('connection')时,使用setInterval推送数据。 Here is the code. 这是代码。

socket.on('connection', function(
    socket.on('handshake', function(socket) {
        console.log("handshake data recieved", socket.id);
        // restart();
        dashboardInterval = setInterval(function(){sendDashboardStats(socket, 'some');}, 5000);
    });
});

This keeps on running, even when the UI/Client has closed the connection. 即使UI / Client关闭了连接,它仍然可以继续运行。 To make matters worse, there could be many users/clients at any given point of time, so how do we close only those intervals? 更糟糕的是,在任何给定的时间点可能会有许多用户/客户端,那么我们如何仅关闭那些间隔?

You could just cancel your interval when you want to or even when socket get disconnected by just adding clearInterval( dashboardInterval ); 您可以通过添加clearInterval( dashboardInterval );来取消间隔,甚至在套接字断开连接时也可以clearInterval( dashboardInterval ); .

var dashboardInterval;

socket.on('connection', function(
  socket.on('handshake', function(socket) {
    console.log("handshake data recieved", socket.id);
    // restart();
    dashboardInterval = setInterval(function() {
      sendDashboardStats(socket, 'some');
    }, 5000);
  });

  socket.on('disconnect', function() {

    if (dashboardInterval) {
      cancelInterval(dashboardInterval);
    }

    io.sockets.emit('user disconnected');
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM