Are calls to Javascript methods thread-safe or synchronized?

Jérôme Verstrynge picture Jérôme Verstrynge · Oct 23, 2011 · Viewed 26.4k times · Source

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

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

Answer

jfriend00 picture jfriend00 · Oct 23, 2011

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.

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

See Do I need to be concerned with race conditions with asynchronous Javascript? for more info.

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