Why does WebSocket event listeners work if they are registered after events are fired?

橙三吉。 提交于 2019-12-06 22:10:40

You can’t add events before an object is created so they have to be afterwards. This all works because JavaScript is single-threaded and events are handled in the same thread so nothing can happen while code is running. You can delay the execution for a year and only after your code finishes will the runtime start handling any events that have arrived while it was running. The socket might not even start connecting before your code finishes.

Therefore it’s guaranteed that no events will go amiss.

Mozilla Developer Network has a good explanation of the event loop, the “Run to Completion” talks about the nature of JS runtime.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!