对 Javascript 方法的调用是线程安全的还是同步的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7868434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are calls to Javascript methods thread-safe or synchronized?
提问by Jér?me Verstrynge
I am still new to Javascript. I am developing a simple page where I click a button fetching a value on a servlet and displays it. It works well, unless I click like crazy on the button. Sometimes, the displayed result is null.
我还是 Javascript 的新手。我正在开发一个简单的页面,我在其中单击一个按钮以获取 servlet 上的值并显示它。它运行良好,除非我疯狂地点击按钮。有时,显示的结果为空。
I am wondering whether this is caused by simultaneous calls to the same following function:
我想知道这是否是由同时调用以下相同函数引起的:
function loadXMLDoc2(retr) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
$("#" + retr).button('option', 'label', xmlhttp.responseText);
// document.getElementById(retr).innerHTML=xmlhttp.responseText;
}
}
var param = "cmd=" + encodeURIComponent(retr);
document.getElementById("TOP_LEFT").innerHTML = param;
xmlhttp.open("GET","/WebFront/Asynclet?" + param,true);
xmlhttp.send(null);
}
Is Javascript thread-safe? And if not, how can I synchronize or isolate calls to this method?
Javascript 线程安全吗?如果没有,我如何同步或隔离对此方法的调用?
回答by jfriend00
Other than HTML5 web workers (which are very tightly controlled), Javascript is single threaded so there are no issues with thread safety. One thread of execution will finish before the next one is started.
除了 HTML5 网络工作者(受到非常严格的控制),Javascript 是单线程的,因此没有线程安全问题。一个执行线程将在下一个线程开始之前完成。
Things like ajax responses go through an event queue and are only executed when any other thread of execution has finished.
诸如 ajax 响应之类的事情通过一个事件队列,并且仅在任何其他执行线程完成时才执行。
See Do I need to be concerned with race conditions with asynchronous Javascript?for more info.
请参阅我是否需要关注异步 Javascript 的竞争条件?了解更多信息。
For a specific discussion of ajax response callbacks see How does JavaScript handle AJAX responses in the background?.
有关 ajax 响应回调的具体讨论,请参阅JavaScript 如何在后台处理 AJAX 响应?.
回答by Pointy
In the context of a browser, JavaScript is essentially single-threaded. (There are some newer browser features that provide a sort of threading model, but thread interactions are very limited and data can't be directly shared.)
在浏览器的上下文中,JavaScript 本质上是单线程的。(有一些较新的浏览器功能提供了一种线程模型,但线程交互非常有限,无法直接共享数据。)