I have a question on when a websocket opens.
it seems to stay pending until the constructor of my class is completed, no matter how much time has passed. Is this an internal browser mechanism or will the following code ever have a race condition?
class TestSockets {
constructor() {
this.csrf = getCSRF()
this.socketURL = "wss://" + window.location.hostname + "/path?csrf=" + this.csrf;
this.WSConnection = new WebSocket(this.socketURL);
wait(10000)
console.log(this.WSConnection.readyState)
this.WSConnection.onmessage = function (e) {
console.log('Server: ' + e.data);
};
wait(10000)
console.log(this.WSConnection.readyState)
}
getMessage1() {
this.WSConnection.send('{"name":"messageinfo","args":[{}]}')
}
getMessage2() {
this.WSConnection.send('{"name":"messageinfo2","args":[{}]}')
}
getMessage3() {
this.WSConnection.send('{"name":"messageinfo3","args":[{}]}')
}
close() {
this.WSConnection.close()
}
}
The usage would be...
let ts = new TestSockets()
ts.getMessage1()
ts.getMessage2()
ts.close()
ignore the usefulness of this at the moment as this is mostly an example so I can get an explanation on when the open occurs. I noticed that the socket was pending up until the constructor ended. I tried a bunch of different things, but I couldn't nail down exactly when the socket is suppose to be opened.
if it was opened because of the constructor closing, is that how websockets work, they open when the scope is complete? or was mine just too fast to see it open async and I have blocking code preventing it?
I am unsure if my code only acts like this because of the constructor or what, any insight into this would be awesome.
edit blocking wait function:
function wait(ms) {
var start = Date.now(),
now = start;
while (now - start < ms) {
now = Date.now();
}
}
edit 2
While searching a bit more I stumbled upon the terminology I was looking for the "event loop", in which I found this...
How does JavaScript handle AJAX responses in the background?
I think this solved, it isn't exactly a duplicate of this question, but I think it answers it anyway. I have marked it as a duplicate.