同步:onerror事件和n++

发布于 2024-09-06 11:08:17 字数 201 浏览 3 评论 0原文

我刚刚阅读了一些 JavaScript 内容,并发现了一些处理加载图像过程的代码:

var n = 0;
...
for (...) {
  ...
  image[i].onload = function { n++; };
}

这段代码安全吗?或者在访问变量 n 时会出现任何类型的竞争吗?

I'm just reading a bit into JavaScript and came over some code that handle the process of loading images:

var n = 0;
...
for (...) {
  ...
  image[i].onload = function { n++; };
}

Is this piece of code safe or can there be any type of race while accessing the variable n?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故事还在继续 2024-09-13 11:08:17

每个图像的 ONLOAD 事件发生的时间(相对于彼此,如果有的话)通常是不确定的。考虑浏览器缓存、并发下载或失败尝试等问题。

但是,一次只有一个 JavaScript“执行上下文”;也就是说,n 的最终值将反映调用 ONLOAD 处理程序的总次数(在给定时间)。也就是说,对于给定的页面,所有 JS 都是原子的,直到完成(在事件发生之前交给浏览器)

“Web Workers”也适合此事件模型;线程和变量访问之间不存在传统的“竞争条件”。然而,任务之间的任何共享(可变)状态都可能导致竞争条件,尽管是在更高级别。

The time at which the ONLOAD event for each image is raised (relatively to each other, if at ever) is generally non-deterministic. Consider issues like browser cache or concurrent downloads, or failed attempts.

However, there is only one JavaScript "execution context" at a time; that is, the final value of n will reflect the total amount of times that ONLOAD handler is invoked (at that given time). That is, for a given page, all JS is atomic until it finishes (yields to the browser until an event occurs)

"Web Workers" also fit within this event model; there is no traditional "race condition" between threads and variable access. However, any shared (mutable) state between tasks can result in a race-condition, albeit at at higher-levels.

万水千山粽是情ミ 2024-09-13 11:08:17

这是非常安全的,因为大多数 JavaScript 都在单线程上下文中运行。唯一需要注意的是 Web Workers,但它们设计得很好,并且只能通过 JSON 消息进行通信。

This is pretty safe since most JavaScript is run in a single threaded context. The only caveat is Web Workers but they are designed quite well and can only communicate via JSON messages.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文