How to automatically reconnect after it dies with WebSocket and JavaScript?

Sometimes, we want to automatically reconnect after it dies with WebSocket and JavaScript

In this article, we’ll look at how to automatically reconnect after it dies with WebSocket and JavaScript.

How to automatically reconnect after it dies with WebSocket and JavaScript?

To automatically reconnect after it dies with WebSocket and JavaScript, we set the WebSocket object’s onclose method to a function that reconnects after a set timeout.

For instance, we write

const connect = () => {
  const ws = new WebSocket("ws://localhost:8080");
  ws.onopen = () => {
    ws.send(
      JSON.stringify({
        //....
      })
    );
  };

  ws.onmessage = (e) => {
    console.log("Message:", e.data);
  };

  ws.onclose = (e) => {
    setTimeout(function () {
      connect();
    }, 1000);
  };

  ws.onerror = (err) => {
    console.error(err.message);
    ws.close();
  };
};

connect();

to create the connect function.

In it, we create a WebSocket object.

We set the onclose property to a function that calls connect in the setTimeout callback after a 1 second delay to reconnect after the connection is closed.

Conclusion

To automatically reconnect after it dies with WebSocket and JavaScript, we set the WebSocket object’s onclose method to a function that reconnects after a set timeout.