I have a code like below:
var ws = new WebSocket("ws://localhost");
ws.onopen = function() {
// Long running loop
for (var i = 0; i < 1000000; i++) {
ws.send(i);
console.log(i);
}
};
The server only receives message (or I believe the client only starts sending message) after the loop gets completed. Why is this so?
Some areas of execution with a page are:
I’ve not tested this for a while, but I’m assuming it is still the case, that if you execute a function (or run code in one scope) then if you make a call to update the DOM or make a network request that won’t happen until the current scope exists.
e.g.
In the code above the following will happen:
doSomethingexecutes and the internal code is run.doSomethingreturns and the scope changesalertfires.Looking specifically at the
WebSocketexample. If you think about the fact we can add event handlers after we create theWebSocketinstance this means that the connection doesn’t occur as soon as we call the constructor. The connection is only attempted when the current scope of executions completes. I can’t 100% confirm this, but it’s also highly unlikely that theWebSocket.sendfunction actually sends any data until the scope of execution completes e.g.In the above code I would expect:
sendStuffto be called, run the loop and exit