It does not look for the onopen function until the end of the execution of the current (synchronous) code. This is because the connection (and thus the onopen callback call) is asynchronous. Consider:
var x = false; setTimeout(function () { x = true }, 1000); while(!x){ console.log('waiting!'); }
The while will never end, but you probably suspect that it will end in one second.
If you delay the initialization of the onopen function by executing time-consuming (but synchronous) code, then this is not dangerous. On the other hand, if you setTimeout onopen initialization, then there is no guarantee whether this was determined or not during the connection to WebSockets, since you cannot be sure which callback will be executed in the first place.
If you were doing the same in C ++, you would use threads for this. In JavaScript, callbacks are not thread-based; it just behaves like a thread (see the endless while loop above).
One thread executes one code block at a time and other code units are queued until the current code block is completed.
source: http://www.slideshare.net/clutchski/writing-asynchronous-javascript-101
It is important to understand that even if you setTimeout something in 1 second, it may not execute after one second. If a thread is busy, it can never be executed.
Thus, if you initiate a connection to WebSocket and run a loop similar to the one above, but waiting for the connection to be ready, it will never end.
This behavior may seem strange to programmers not familiar with JS. Therefore, for readability, I define callbacks at the same time or immediately after the functions they need when possible.
If you want to explicitly use threads and concurrent execution, read more about web workers
Reference:
Michał Miszczyszyn
source share