Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I handle WebSocket disconnections and automatically reconnect using JavaScript in the browser? Pending Review
Asked on Jan 16, 2026
Answer
To handle WebSocket disconnections and automatically reconnect in the browser, you can create a function that manages the connection and attempts to reconnect when the connection is lost.
<!-- BEGIN COPY / PASTE -->
let socket;
const url = "wss://example.com/socket";
const reconnectInterval = 5000; // 5 seconds
function connect() {
socket = new WebSocket(url);
socket.onopen = () => {
console.log("Connected to WebSocket server");
};
socket.onmessage = (event) => {
console.log("Message from server:", event.data);
};
socket.onclose = () => {
console.log("Disconnected from WebSocket server, attempting to reconnect...");
setTimeout(connect, reconnectInterval);
};
socket.onerror = (error) => {
console.error("WebSocket error:", error);
socket.close();
};
}
connect();
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- This code defines a "connect" function that initializes a WebSocket connection to the specified URL.
- The "onopen" event handler logs a message when the connection is successfully established.
- The "onmessage" event handler processes incoming messages from the server.
- The "onclose" event handler attempts to reconnect after a specified interval when the connection is closed.
- The "onerror" event handler logs errors and closes the socket to trigger the reconnection logic.
Recommended Links:
