对 Javascript 方法的调用是线程安全的还是同步的? [英] Are calls to Javascript methods thread-safe or synchronized?

查看:40
本文介绍了对 Javascript 方法的调用是线程安全的还是同步的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是 Javascript 的新手.我正在开发一个简单的页面,我在其中单击一个按钮以获取 servlet 上的值并显示它.它运行良好,除非我疯狂地点击按钮.有时,显示结果为空.

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.

我想知道这是否是由同时调用以下相同函数引起的:

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);
}

Javascript 线程安全吗?如果没有,我如何同步或隔离对此方法的调用?

Is Javascript thread-safe? And if not, how can I synchronize or isolate calls to this method?

推荐答案

除了 HTML5 web workers(控制非常严格,显然不是你要问的),浏览器中的 Javascript 是单线程的,所以常规的 Javascript 编程可以没有线程安全问题.一个执行线程将在下一个线程开始之前完成.没有两个 Javascript 完全同时运行.

Other than HTML5 web workers (which are very tightly controlled and not apparently what you are asking about), Javascript in the browser is single threaded so regular Javascript programming does not have thread safety issues. One thread of execution will finish before the next one is started. No two pieces of Javascript are running at exactly the same time.

像 ajax 响应这样的事情通过一个事件队列,并且只有在任何其他执行线程完成时才会执行.

Things like ajax responses go through an event queue and are only executed when any other thread of execution has finished.

参见我需要关注异步 Javascript 的竞争条件吗? 了解更多信息.

有关 ajax 响应回调的具体讨论,请参阅 JavaScript 如何在后台处理 AJAX 响应?.

For a specific discussion of ajax response callbacks see How does JavaScript handle AJAX responses in the background?.

这篇关于对 Javascript 方法的调用是线程安全的还是同步的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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