同步:onerror事件和n++
我刚刚阅读了一些 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每个图像的 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.
这是非常安全的,因为大多数 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.