I'm still new to Javascript and I'm trying to work with WebSockets. I have a working skeleton of an application, though it still has issues I need to resolve.
How can I signal to the rest of the application that the web socket is ready for use?
socket = new WebSocket( 'wss://' + window.location.host + '/ws/manager/' );
while (socket.readyState != 1){
// wait loop
}
When the socket is created it returns immediately, but is not yet ready for communication. My first thought was that I just loop while checking the status, which is my current solution, but that just burns CPU and would make the application unresponsive. Introducing a delay would resolve some responsiveness, but that has its own issues as shown here: What is the JavaScript version of sleep()? for example . I also understand that looping to wait is a no no.
The other solution I saw was to use setTimeout()
and a callback to continue execution, but I feel like that would be very disruptive to the code reading and writing, and possibly still not entirely solve the issue in a better way.
This will be a one page application, and the server communication will be done almost entirely with web sockets due to the sheer number of connections that would be required with ajax or conventional HTTP. In general, I don't really mind that the app would become unresponsive, since without the web socket it would be pretty useless anyway.