Search code examples
javascriptdom-eventslanguage-agnostic

When are Javascript events executed?


When I look at JS code like:

socket = new WebSocket(server);

socket.onopen = function (evt) 
{
        // STUFF
};

I'm always a little bit confused. If you wrote something like that in any other language, there would be a very huge chance of the onopen 'eventhandler' being bound AFTER the connection to server already being established, causing you to miss the onopen event. Even if first line was executed asynchronously by the Javascript interpreter, there was still a slight chance of being too late on the second line.

Why does the above code run fine in Javascript while in C# (for example) it should be written as:

WebSocket socket = new WebSocket();

socket.onopen = new EventHandler<EventArgs>(Open);

socket.Connect(server);

Solution

  • Unlike most other languages, Javascript is strictly single-threaded.
    While your code is running, nothing else can happen.

    onopen cannot fire until control returns to the event loop (after the synchronous portion of that code has finished).

    Note that this is true because onopen is fired in response to an asynchronous event (in this case, a socket).
    If it were raised synchronously, that would not be true; to fix this, code that synchronously raises events used with this pattern should raise the event asynchronously in process.nextTick.