'Alert inside websocket open event

I have this code that alert("open") is displayed ok.

var webSocket = new WebSocket("ws://localhost:8080/WebSocketServerExample/websocketendpoint");
webSocket.onopen = function(message){ alert("open");};          
But when I add one more alert after webSocket creation then the same alert("open") doesn't appear
var webSocket = new WebSocket("ws://localhost:8080/WebSocketServerExample/websocketendpoint");
alert("after websoscket creation");
webSocket.onopen = function(message){ alert("open");};      

Has it to do with threads?

UPDATE: If we replace the alert inside onopen event with console.log then again nothing appears in console. This means that all the code inside onopen doesn't run so this leads us to assume that the event is not triggered. Why?



Solution 1:[1]

The sequence of execution is:

  1. var websocket = new WebSocket(...);
  2. alert("after websoscket creation");
  3. webSocket.onopen();
  4. alert("open");

i.e., the onopen callback is executed after your first alert. That means, that the first alert is open while the second is launched, and in the browser, a second alert is blocked when there is already one open.

Solution 2:[2]

I think that we missed out the onopen event. There is 2 links that has to do with this.

javascript websockets - control initial connection/when does onOpen get bound

Also a very good explanation of code execution:https://bytefish.medium.com/the-execution-order-of-asynchronous-functions-in-the-event-loop-ff641dae4f09

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nechoj
Solution 2