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

查看:180
本文介绍了调用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网络工作者(非常紧密) javascript是单线程的,因此线程安全没有问题。一个执行线程将在下一个执行之前完成。

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.

像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天全站免登陆