javascript - Why does WebSocket event listeners work if they are registered after events are fired? - Stack Overflow

According to MDN docs, the WebSocket event listeners are registered after the connection is created, an

According to MDN docs, the WebSocket event listeners are registered after the connection is created, and the process is sequential:

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    console.log('ws connected');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

How does this work if events start firing before the listeners were registered? Say, the connection opened before the open listener is registered, or messaged came in before the message listener is registered.

I would expect the events to be lost since the event listeners are not registered yet, according to the MDN doc on Concurrency model and Event Loop:

In web browsers, messages are added anytime an event occurs and there is an event listener attached to it. If there is no listener, the event is lost. So a click on an element with a click event handler will add a message--likewise with any other event.

I tried to add some expensive ops in between, but it seems that the open and message event listeners only trigger after all the event listeners are properly registered. Are the WebSocket features async in nature?

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// expensive ops
for (var i = 5000; i >= 0; i--) {
  console.log('1');
}

// Connection opened
socket.addEventListener('open', function (event) {
    console.log('ws connected');
});

// expensive ops
for (var i = 5000; i >= 0; i--) {
  console.log('2');
}

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

// prints "1"s, then "2"s, then "ws connected", then "Message from server"

According to MDN docs, the WebSocket event listeners are registered after the connection is created, and the process is sequential:

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    console.log('ws connected');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

How does this work if events start firing before the listeners were registered? Say, the connection opened before the open listener is registered, or messaged came in before the message listener is registered.

I would expect the events to be lost since the event listeners are not registered yet, according to the MDN doc on Concurrency model and Event Loop:

In web browsers, messages are added anytime an event occurs and there is an event listener attached to it. If there is no listener, the event is lost. So a click on an element with a click event handler will add a message--likewise with any other event.

I tried to add some expensive ops in between, but it seems that the open and message event listeners only trigger after all the event listeners are properly registered. Are the WebSocket features async in nature?

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// expensive ops
for (var i = 5000; i >= 0; i--) {
  console.log('1');
}

// Connection opened
socket.addEventListener('open', function (event) {
    console.log('ws connected');
});

// expensive ops
for (var i = 5000; i >= 0; i--) {
  console.log('2');
}

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

// prints "1"s, then "2"s, then "ws connected", then "Message from server"
Share Improve this question edited Feb 13, 2019 at 8:28 paradite asked Feb 13, 2019 at 6:32 paraditeparadite 6,4364 gold badges42 silver badges61 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745635897a4637389.html

相关推荐

  • 取消Win10开机系统选择倒计时,让电脑秒进系统

    取消Win10开机系统选择倒计时,让电脑秒进系统 近期,不少Win10用户反映在开机时会遇到一个选择系统的倒计时画面,这在一定程度上延缓了开机进程。对于追求高效启动体验的用户来说,这无疑是一个不必要的步骤。那么,如何取消这个倒计时,让电脑

    1小时前
    00
  • PyMC+AI提示词贝叶斯项目反应IRT理论Rasch分析篮球比赛官方数据:球员能力与位置层级结构研究

    全文链接:tecdat?p=41666在体育数据分析领域不断发展的当下,数据科学家们致力于挖掘数据背后的深层价值,为各行业提供更具洞察力的决策依据。近期,我们团队完成了一项极具意义的咨询项目,旨在通过先进的数据分析手段,深入探究篮球比赛中

    1小时前
    00
  • 聊聊Spring AI Alibaba的ObsidianDocumentReader

    序本文主要研究一下Spring AI Alibaba的ObsidianDocumentReaderObsidianDocumentReadercommunitydocument-readersspring-ai-alibaba-star

    1小时前
    00
  • PackML over OPC UA

    在当今数字化转型的浪潮中,制造业正面临着前所未有的挑战与机遇。如何实现设备之间的高效通信与集成,成为提升生产效率、降低成本的关键。OPC UA(OPC Unified Architecture)与PackML(Packaging Machi

    1小时前
    00
  • 1.8w字图解Java并发容器: CHM、ConcurrentLinkedQueue、7 种阻塞队列的使用场景和原理

    文章多图且内容硬核,建议大家收藏上一章《1.6w 字图解 Java 并发:多线程挑战、线程状态和通信、死锁;AQS、ReentrantLock、Condition 使用和原理》,我们开启了 Java 高并发系列的学习,透彻理解 Java 并

    1小时前
    00
  • 电脑密码在哪里设置win11,win11电脑开机密码怎么设置

    Win11系统由于许多设置和以前系统不一样了,所以很多用户们操作非常不习惯,有很多的小伙伴不知道win11系统怎么设置开机密码。给电脑设置密码,只有自己能打开进入系统桌面&a

    1小时前
    00
  • HLS最全知识库

    HLS最全知识库副标题-FPGA高层次综合HLS(二)-Vitis HLS知识库高层次综合(High-level Synthesis)简称HLS,指的是将高层次语言描述的逻辑结构,自动转换成低抽象级语言描述的电路模型的过程。对于AMD Xi

    1小时前
    00
  • 我用AI监控了奥特曼,当他一发推特AI就会自动给我打电话。

    上周我真的扛不住了。奥特曼这个孙贼,发了个X说,“要发一个礼拜的好东西”。我信了他的邪,明明出差1周,每天早上9点不到就要起来参加活动,但是晚上根本不敢睡觉,天天蹲到凌晨3点半,蹲到他们那边时间中午12点多,我才敢去睡觉。真的,那一整周,我

    59分钟前
    00
  • 面试官:从三万英尺角度谈一下Ceph架构设计(1)

    把面试官当陪练,在找工作中才会越战越勇大家好我是小义同学,这是大厂面试拆解——项目实战系列的第3篇文章,如果有误,请指正。本文主要解决的一个问题,Ceph为例子 如何描述项目的架构。一句话描述:主要矛盾发生变化10年前的技术和方案,放到10

    56分钟前
    00
  • 电脑开机会默认一件GHOST

    关于电脑开机会自己重装系统 前段时间电脑一开机就遇到会自己ghost的问题,而且一直再重复同样的操作,我点击restart的时候到开启页面又会自动ghost,而且此页面停留

    50分钟前
    00
  • ascend pytorch 踩坑.

    在910b上安装pytorch 和 pytorch_npu, 因为后续准备装vllm, 所以torch_npu是特殊的版本.代码语言:shell复制pip install torch==2.5.1 --extra-index pip in

    40分钟前
    00
  • 开源在线考试系统

    看到调问已经开始扩展在线考试的场景,试了一下,发现在线考试的基本能力都已经支持了。主要是考试中的各种计分功能,包括对每道题的选项设置分值计算、考试时间限制等,和官方了解了一下,考试中的其他各项能力也在逐步完善,有需求可以随时

    38分钟前
    00
  • Power BI 无公式实现帕累托图表

    帕累托分析(Pareto Analysis),也被称为8020法则、关键少数法则,是一种常用的管理工具,用于识别和处理影响业务的主要因素。看到李伟坚老师在Excel使用Vega实现了花式帕累托(参考:Excel 零公式实现高级帕累托图表)

    37分钟前
    00
  • 深度学习在DOM解析中的应用:自动识别页面关键内容区块

    爬虫代理摘要本文介绍了如何在爬取东方财富吧()财经新闻时,利用深度学习模型对 DOM 树中的内容区块进行自动识别和过滤,并将新闻标题、时间、正文等关键信息分类存储。文章聚焦爬虫整体性能瓶颈,通过指标对比、优化策略、压测数据及改进结果,展示了

    29分钟前
    10
  • 推荐一个轻量级的监控平台并且支持移动端

    简介XUGOU 是基于Cloudflare构建的轻量化监控平台,专精于系统资源监控与可视化状态页面服务。该平台提供英文简体中文双语支持,满足全球化部署需求。面向开发者及中小团队,项目致力于提供高可用性的监控解决方案。核心功能与实现平台功能

    24分钟前
    00
  • 拥抱国产化:转转APP的鸿蒙NEXT端开发尝鲜之旅

    本文由转转技术团队赵卫兵分享,原题“鸿蒙新篇章:转转 APP 的 HarmonyOS Next 开发之旅”,下文进行了排版优化和内容修订。1、引言2023 年在华为开发者大会(HDC.Together)上,除了面向消费者的 HarmonyO

    18分钟前
    00
  • 在VMware虚拟机中安装Windows 7全攻略(避坑指南)

    ⚠️写在前面 最近发现很多开发者在调试老旧系统时都需要用到Windows 7环境(特别是银行、医疗等行业的遗留系统),但实体机安装既不现实也不安全。今天就手把手教你在虚拟机

    12分钟前
    00
  • windows新建open ai密钥

    api链接 openai的api需要付费才能使用但好像系统变量不知道为啥用不了打印出来,获取到的是None可以用了

    11分钟前
    00
  • 1.54G 雨晨 26100.3775 Windows 11 IoT 企业版 LTSC 24H2 极速版

    精简AERO外主题并增加一套壁纸主题(默认启用)误杀导致功能界面空白、因WMIC被默认移除系统可能会多次重启。 拒止连接 www.5909 拒止连接 www.mnpc 拒止连接 quark 拒止

    6分钟前
    00
  • 人工智能应用领域有哪些

    人工智能应用领域有哪些一、引言随着科技的飞速发展,人工智能(AI)已经逐渐渗透到我们生活的方方面面,成为推动社会进步的重要力量。从医疗健康到金融服务,从教育学习到智能制造,人工智能以其独特的技术优势,为各行各业带来了前所未有的变革。本文旨在

    34秒前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信