I am doing the following to prepare my WebSocket for use in many other places, not just immediately after the WebSocket readyState changes:
// https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
const sleep = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
};
// (inside of async function)...
const ws = new WebSocket(<webSocketServerUri>);
let timeToConnect = 0;
while (ws.readyState !== ws.OPEN) {
await sleep(1);
++timeToConnect;
};
console.log('The WebSocket took ' + timeToConnect + ' milliseconds to connect.');
// (inside of async function)...
// ...
// (some other place in the code where 'ws' is accessible)...
ws.send('my msg');
// (some other place in the code where 'ws' is accessible)...