JavaScript 是否保证是单线程的? [英] Is JavaScript guaranteed to be single-threaded?

查看:22
本文介绍了JavaScript 是否保证是单线程的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,在所有现代浏览器实现中,JavaScript 都是单线程的,但这是在任何标准中指定的还是只是按照传统?假设 JavaScript 总是单线程的是否完全安全?

JavaScript is known to be single-threaded in all modern browser implementations, but is that specified in any standard or is it just by tradition? Is it totally safe to assume that JavaScript is always single-threaded?

推荐答案

这是个好问题.我很想说是".我不能.

That's a good question. I'd love to say "yes". I can't.

JavaScript 通常被认为具有对脚本 (*) 可见的单个执行线程,因此当您进入内联脚本、事件侦听器或超时时,您将保持完全控制,直到您从块的末尾返回或功能.

JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.

(*:忽略浏览器是否真的使用一个操作系统线程来实现他们的 JS 引擎的问题,或者 WebWorkers 是否引入了其他有限的执行线程.)

(*: ignoring the question of whether browsers really implement their JS engines using one OS-thread, or whether other limited threads-of-execution are introduced by WebWorkers.)

然而,实际上这并不完全正确,以一种偷偷摸摸的讨厌的方式.

However, in reality this isn't quite true, in sneaky nasty ways.

最常见的情况是即时事件.当您的代码执行某些操作导致它们时,浏览器会立即触发它们:

The most common case is immediate events. Browsers will fire these right away when your code does something to cause them:

var l= document.getElementById('log');
var i= document.getElementById('inp');
i.onblur= function() {
    l.value+= 'blur
';
};
setTimeout(function() {
    l.value+= 'log in
';
    l.focus();
    l.value+= 'log out
';
}, 100);
i.focus();

<textarea id="log" rows="20" cols="40"></textarea>
<input id="inp">

导致 log in, blur, log out 除了 IE.这些事件不只是因为你直接调用了 focus() 而触发,它们可能因为你调用了 alert(),或者打开了一个弹出窗口,或其他任何东西而发生移动焦点.

Results in log in, blur, log out on all except IE. These events don't just fire because you called focus() directly, they could happen because you called alert(), or opened a pop-up window, or anything else that moves the focus.

这也可能导致其他事件.例如添加一个 i.onchange 侦听器并在 focus() 调用取消焦点之前在输入中键入一些内容,并且日志顺序是 log in, change,模糊,注销,除了在 Opera 中,它是 login,blur,log out,change 和 IE(甚至不太明确)login,change,log out,模糊.

This can also result in other events. For example add an i.onchange listener and type something in the input before the focus() call unfocuses it, and the log order is log in, change, blur, log out, except in Opera where it's log in, blur, log out, change and IE where it's (even less explicably) log in, change, log out, blur.

类似地在提供它的元素上调用 click() 会立即在所有浏览器中调用 onclick 处理程序(至少这是一致的!).

Similarly calling click() on an element that provides it calls the onclick handler immediately in all browsers (at least this is consistent!).

(我在这里使用了直接的 on... 事件处理程序属性,但对于 addEventListenerattachEvent 也是如此.)

(I'm using the direct on... event handler properties here, but the same happens with addEventListener and attachEvent.)

还有很多情况,在您的代码被线程化时,事件可能会被触发,尽管您没有做任何事情来激起它.一个例子:

There's also a bunch of circumstances in which events can fire whilst your code is threaded in, despite you having done nothing to provoke it. An example:

var l= document.getElementById('log');
document.getElementById('act').onclick= function() {
    l.value+= 'alert in
';
    alert('alert!');
    l.value+= 'alert out
';
};
window.onresize= function() {
    l.value+= 'resize
';
};

<textarea id="log" rows="20" cols="40"></textarea>
<button id="act">alert</button>

点击alert,你会得到一个模态对话框.在您关闭该对话之前不会再执行脚本,是吗?不.调整主窗口的大小,您将在文本区域中获得alert in, resize, alert out.

Hit alert and you'll get a modal dialogue box. No more script executes until you dismiss that dialogue, yes? Nope. Resize the main window and you will get alert in, resize, alert out in the textarea.

您可能认为在模式对话框打开时调整窗口大小是不可能的,但事实并非如此:在 Linux 中,您可以随意调整窗口大小;在 Windows 上,这不是那么容易,但是您可以通过将屏幕分辨率从较大更改为较小的窗口不适合,从而调整其大小来实现.

You might think it's impossible to resize a window whilst a modal dialogue box is up, but not so: in Linux, you can resize the window as much as you like; on Windows it's not so easy, but you can do it by changing the screen resolution from a larger to a smaller one where the window doesn't fit, causing it to get resized.

您可能会认为,当用户没有与浏览器进行主动交互时,只有 resize(可能还有一些更像 scroll)可以触发因为脚本是线程化的.对于单个窗口,您可能是对的.但是,只要您在进行跨窗口脚本编写,这一切就都付诸东流了.对于除 Safari 之外的所有浏览器,当它们中的任何一个忙时,它会阻止所有窗口/选项卡/框架,您可以从另一个文档的代码与文档交互,在单独的执行线程中运行并导致任何相关的事件处理程序火.

You might think, well, it's only resize (and probably a few more like scroll) that can fire when the user doesn't have active interaction with the browser because script is threaded. And for single windows you might be right. But that all goes to pot as soon as you're doing cross-window scripting. For all browsers other than Safari, which blocks all windows/tabs/frames when any one of them is busy, you can interact with a document from the code of another document, running in a separate thread of execution and causing any related event handlers to fire.

在脚本仍然线程化时可以引发生成事件的地方:

Places where events that you can cause to be generated can be raised whilst script is still threaded:

  • 当模态弹出窗口(alertconfirmprompt)在所有浏览器中打开时;

  • when the modal popups (alert, confirm, prompt) are open, in all browsers but Opera;

在支持它的浏览器上的 showModalDialog 期间;

during showModalDialog on browsers that support it;

此页面上的脚本可能正忙..."对话框,即使您选择让脚本继续运行,也允许触发和处理诸如调整大小和模糊之类的事件,即使在脚本执行期间处于繁忙循环的中间,除了在 Opera 中.

the "A script on this page may be busy..." dialogue box, even if you choose to let the script continue to run, allows events like resize and blur to fire and be handled even whilst the script is in the middle of a busy-loop, except in Opera.

对我来说,不久前,在带有 Sun Java 插件的 IE 中,调用小程序上的任何方法都可能允许触发事件并重新输入脚本.这一直是一个对时间敏感的错误,而且 Sun 可能已经修复了它(我当然希望如此).

a while ago for me, in IE with the Sun Java Plugin, calling any method on an applet could allow events to fire and script to be re-entered. This was always a timing-sensitive bug, and it's possible Sun have fixed it since (I certainly hope so).

可能更多.自从我测试这个已经有一段时间了,浏览器变得越来越复杂.

probably more. It's been a while since I tested this and browsers have gained complexity since.

总而言之,在大多数情况下,JavaScript 对大多数用户来说似乎具有严格的事件驱动单线程执行.实际上,它没有这样的东西.目前尚不清楚这其中有多少只是一个错误,有多少是故意设计的,但是如果您正在编写复杂的应用程序,尤其是跨窗口/框架脚本的应用程序,那么它很有可能会咬到您 — ,并且间歇性地,难以调试的方式.

In summary, JavaScript appears to most users, most of the time, to have a strict event-driven single thread of execution. In reality, it has no such thing. It is not clear how much of this is simply a bug and how much deliberate design, but if you're writing complex applications, especially cross-window/frame-scripting ones, there is every chance it could bite you — and in intermittent, hard-to-debug ways.

最坏的情况下,您可以通过间接处理所有事件响应来解决并发问题.当一个事件进来时,把它放到一个队列中,然后在一个 setInterval 函数中按顺序处理这个队列.如果您正在编写一个打算供复杂应用程序使用的框架,那么这样做可能是一个不错的举措.postMessage 也有望在未来缓解跨文档脚本的痛苦.

If the worst comes to the worst, you can solve concurrency problems by indirecting all event responses. When an event comes in, drop it in a queue and deal with the queue in order later, in a setInterval function. If you are writing a framework that you intend to be used by complex applications, doing this could be a good move. postMessage will also hopefully soothe the pain of cross-document scripting in the future.

这篇关于JavaScript 是否保证是单线程的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆