WebSocket uses the TCP protocol which means that messages always arrive in the order they were sent. There is no such thing as a "message collision".
There is only one thread to process events, you can create a background thread called a WebWorker to handle the WebSocket connection (including creating the connection, sending and receiving). But then interacting with the rest of your Javascript, including the DOM, is complicated.
To process the messages assign socket.onmessage
immediately after creating the socket. The function you assign to socket.onmessage
will receive the messages in the order they arrive. Look for a WebSocket tutorial to see how.