Skip to content

Instantly share code, notes, and snippets.

@ndrbrt
Last active April 12, 2024 18:19
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndrbrt/4fb9af2084316ac0c0f9d3c46b9f2d02 to your computer and use it in GitHub Desktop.
Save ndrbrt/4fb9af2084316ac0c0f9d3c46b9f2d02 to your computer and use it in GitHub Desktop.
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)
}
}
@ghasemhasani
Copy link

asdfsad

@jcarocota
Copy link

Merci

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment