I try to write a function which connects to the WebSocket server. The problem occurs when this server is down. This function should wait for it, even for long time, but it shouldn't consume 100% of CPU. Here is my code:
var state = {
connected: false
};
var settings = {
host: 'localhost',
port: 1988
};
function connect(settings) {
try {
var socket;
var host = 'ws://' + settings.host + ':' + settings.port;
var socket = new WebSocket(host);
socket.onopen = function() {
state.connected = true;
}
// socket.onmessage
socket.onclose = function() {
state.connected = false;
connect(settings);
}
} catch(e){
console.log(e);
}
}
So I need to somehow pass an interval to the WebSocket constructor, it looks like it simply tries to open a connection in a loop, killing performance. How can I do that?
The socket is immediately closing when you attempt to connect, causing you to try to connect again. Add an interval between tries:
socket.onclose = function() {
state.connected = false;
setInterval(function() {
connect(settings);
}, 1000);
}