I’ve been trying to understand some code used to open a websocket:
var ws = new WebSocket('ws://my.domain.com');
ws.onopen = function(event) {
...
}
My question is how does the handshaking get started? If it is started in the WebSocket constructor, then how does onopen get called if it isn’t set by then? If the WebSocket constructor creates a thread that does the handshaking, then does onopen have to be defined quickly enough before the handshaking is over? If so, that sounds a little dangerous because if the JS virtual machine is slowed the handshaking could be finished before onopen is defined, which means that the event is not handled. Or does setting the onopen function trigger the handshaking?
Could someone explain to me the mechanics of the API please?
It does not look for
onopenfunction until end of execution of current (synchronous) code. That is because the connection (and thus callingonopencallback) is asynchronous.Consider:
The
whileloop there will never end but you would probably suspect it’d end after one second.If you delay the initialisation of
onopenfunction by executing time-consuming (but synchronous) code then it is not dangerous. On the other if yousetTimeoutinitialisation ofonopenthen there’s no guarantee whether it’s defined or not at the time the WebSockets connection is ready as you can’t be sure which callback will be executed first.If you were doing the same thing in C++ you’d use threads for that. In JavaScript callbacks mechanism is not thread-based; it just behaves thread-like (see the endless while loop above).
source: http://www.slideshare.net/clutchski/writing-asynchronous-javascript-101
It’s important to understand that even if you
setTimeoutsomething for 1s it might not execute after one second – If the thread is busy it might never get executed.Thus if you initiate WebSocket connection and run a loop similar to the one above but waiting for the connection to be ready it might never end.
This behaviour might look strange for programmers not familiar with JS. Therefore for readability I define callbacks at the same time or immediately after the functions which need them whenever it’s possible.
If you want to explicitly use threads and concurrent execution, read more about Web Workers
Reference: