Search code examples
javascriptnullthread-safetysynchronized

Are calls to Javascript methods thread-safe or synchronized?


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?


Solution

  • 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.

    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?.