javascript - How can I be sure I don't miss the "open" event on WebSockets? -
this question has answer here:
this more of abstract question really. how can sure don't miss websocket's open event? understand it, browser starts establishing connection call constructor, if things go badly, open (or error) event might fired before handlers events connected.
var socket = new websocket("ws://www.example.com"); /*because i'm unlucky guy, open-event fires before next line*/ socket.addeventlistener("open", function(event){...});
in case, open-handler never called. never real problem because establishing connection takes longer executing next line of javascript. however, same said xmlhttprequest, , there recommended order of things is:
var ajax = new xmlhttprequest(); ajax.addeventlistener("load", function(event){...}); ajax.open(); ajax.send();
this makes sure event can not lost. why websocket different in respect? overlooking , missing event not issue?
thank clarification on this.
your second example ajax has faulty assumption. ajax, there no actual problem putting event handler after send
call, long both included in same synchronous set of operations. here's fiddle sends ajax request, burns several seconds (plenty of time fetch complete) , then attaches listeners. can see, events fire fine.
so, okay:
var ajax = new xmlhttprequest(); ajax.open(); ajax.send(); ajax.addeventlistener("load", function(event){...});
due single-threaded nature of browser javascript, load
event not fire until current code finished running. (note: maybe behavior different in older browsers, it's how works in browser supports websockets.)
this, however, not okay:
var ajax = new xmlhttprequest(); ajax.open(); ajax.send(); settimeout(function() { ajax.addeventlistener("load", function(event){...}); }, 1000);
this because you've created race condition between 2 asynchronous actions: settimeout
resolution , load
event firing. long delay between firing ajax request , setting listener in same synchronous execution, there no risk of "missing" ajax event.
it works same way websockets -- can't miss open
event long construct websocket
, attach listener in same synchronous set of instructions. here's fiddle analogous synchronous wait websocket. can see, after waiting several seconds attach event listener, still fires.
i'm not sure practice of "attach listeners before act" comes from. perhaps important in older browsers, or perhaps important apis other ajax. whatever reason practice came about, don't need adhere in modern browsers either ajax or websockets.
Comments
Post a Comment