Question

I'm new to web development and have been reading up on AJAX so that I can update a map live with new data. I'm reading an IBM article on Comet. They provide an implementation for Apache Tomcat.

Article : http://www.ibm.com/developerworks/web/library/wa-cometjava/#resources

The JavaScript code they provide is as follows..

<SCRIPT TYPE="text/javascript">
            function go(){
                var url = "http://localhost:8484/WeatherServer/Weather"
                var request =  new XMLHttpRequest();
                request.open("GET", url, true);
                request.setRequestHeader("Content-Type","application/x-javascript;");
                request.onreadystatechange = function() {
                    if (request.readyState == 4) {
                        if (request.status == 200){
                            if (request.responseText) {
                                document.getElementById("forecasts").innerHTML = 
request.responseText;
                            }
                        }
                        go();
                    }
                };
                request.send(null);
            }
        </SCRIPT>
    </head>
    <body>
        <h1>Rapid Fire Weather</h1>
        <input type="button" onclick="go()" value="Go!"></input>
        <div id="forecasts"></div>
    </body>

I understand all this but have a few questions.

1) Does request.send() spawn a new thread? 2) Will the recursive call to go() eventually cause a stack overflow?

Was it helpful?

Solution

A new thread will be created when you do request.send() Unless you specify explicitly not to in the open-method.

The call to go will never cause a stackoverflow-exception. This is because it is called in a callback and the call stack will be reset when the data returns. It may look like a recursive function, but it's not. Although it's defined inside the go-function, the execution-context will be completely different.

OTHER TIPS

go() will only be executed when the request was successful so you should only have one request at a time I don't think it would cause a stack overflow but a recursive function can cause it just like in any other language. In JavaScript the Ajax request can be executed in async or not async mode the last parameter on open() method will determine the mode to be used you can find more details here http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp hope it helps :)

request.send() is asynchronous -- whether it spawn a new thread internally or reuse some existing one is an implementation detail, but when the last parameter to request.open is true it should be async.

As request.send() is async, onreadystatechange call (that will happen later on) will not share stack with original go. So I would expect stack overflow to be impossible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top