How to wait for a WebSocket's readyState to change
I'm trying to implement a WebSocket with a fallback to polling. If the WebSocket connection succeeds, readyState becomes 1, but if it fails, readyState is 3, and I should begin polling. I tried something like this: var socket = new WebSocket(url); socket.onmessage = onmsg; while (socket.readyState == 0) { } if (socket.readyState != 1) { // fall back to polling setInterval(poll, interval); } I was expecting socket.readyState to update asynchronously, and allow me to read it immediately. However, when I run this, my browser freezes (I left it open for about half a minute before giving up). I