Last active
October 6, 2024 21:51
-
-
Save ndrbrt/4fb9af2084316ac0c0f9d3c46b9f2d02 to your computer and use it in GitHub Desktop.
Wait for the WebSocket connection to be open, before sending a message.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
asdfsad