Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wait for the WebSocket connection to be open, before sending a message.
const waitForOpenConnection = (socket) => {
return new Promise((resolve, reject) => {
const maxNumberOfAttempts = 10
const intervalTime = 200 //ms
let currentAttempt = 0
const interval = setInterval(() => {
if (currentAttempt > maxNumberOfAttempts - 1) {
clearInterval(interval)
reject(new Error('Maximum number of attempts exceeded'))
} else if (socket.readyState === socket.OPEN) {
clearInterval(interval)
resolve()
}
currentAttempt++
}, intervalTime)
})
}
const sendMessage = async (socket, msg) => {
if (socket.readyState !== socket.OPEN) {
try {
await waitForOpenConnection(socket)
socket.send(msg)
} catch (err) { console.error(err) }
} else {
socket.send(msg)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment