title: websocket ping with node js
body: <p>I am learning on how to use websockets. I am returning data to the front-end from the server via normal <code>ws.send</code> but I would at the same time I would like to have a set interval time to ping the front-end to see if clints are still alive there.. This is the code I am using at the moment.</p>
  
  <pre><code>ws.on('connection', function connection(ws, req) {
  
    ws.on('message', function incoming(message) {
      return_data = message;
      heart_beat = {status:"Accepted", currentTime:"2013-02-01T20:53:32.486Z", "heartbeatInterval":300}
  
      ws.send(JSON.stringify(heart_beat));
      const interval = setInterval(function ping() {
      ws.clients.forEach(function each(ws) {
        if (ws.isAlive === false) return ws.terminate();
  
          ws.isAlive = false;
          ws.ping('', false, true);
        });
    }, 300);
    });
  });
  </code></pre>
  
  <p>I want to just wait 300 seconds, if there is no response from the front-end I will terminate the websocket after the first heartbeat send by me</p>
  
  <p>Here is my front-end code.</p>
  
  <pre><code>ws.onopen = function(){
      console.log("Connected");
  }
  ws.onclose = function(){
      console.log("Disconnected");
      ws.send('Disconnected');
  }
  </code></pre>
  
  <p>Whats happening now is that, when I close the browser in the front-end the server in the back-end is still pinging, if I console.log it.</p>