setTimeOut() is not working with AJAX

Devi picture Devi · Sep 19, 2009 · Viewed 8.6k times · Source

In my application i want to send something to the server after some time. I have implemented it using AJAX. But it works for the first time but not doing it recursively. I have used setTimeOut() for doing that.

    var xmlHttp;
    var requestURL = 'http://localhost:1092/ClassicAJAXDemo/UpdateHeartbeat.aspx?name=';

    function show_data(strName)
    {
        if (strName.length > 0)
        {
            var url = requestURL + strName;
            xmlHttp = GetXmlHttpObject(stateChangeHandler);
            xmlHttp_Get(xmlHttp, url);
        }
    }
    function stateChangeHandler()
    {
        if (xmlHttp.readyState == 4)
        {
            var str = xmlHttp.responseText;
            setTimeOut(show_data('Dev'), 10000); // It is not waiting for 10 seconds.
        }
    }

    function xmlHttp_Get(xmlhttp, url)
    {
        xmlhttp.open('GET', url, true);
        xmlhttp.send(null);
    }

    function GetXmlHttpObject(handler)
    {
        return new XMLHttpRequest();
    }
    window.onload = show_data('Dev');

Answer

gnarf picture gnarf · Sep 19, 2009

You have a couple of issues in this code segment that are creating your bugs:

window.onload = show_data('Dev');

A bit of explanation about why window.onload = show_data('Dev'); doesn't work is probably in order: window.onload needs to be a function. As your code executes, it is evaluating show_data('Dev') (which doen't return a value, but does start an XMLHTTPRequest, so it appears to work) and executing window.onload = undefined;.

window.onload=show_data; would work - but then you don't get your parameter passed.

Luckily JavaScript allows you to create anonymous functions - leading to:

window.onload = function() { show_data('Dev'); };

setTimeOut(show_data('Dev'), 10000);

First of all, JavaScript is a case sensitive language. setTimeOut !== setTimeout. Also the first parameter to setTimeout/setInterval is expected to be a function, which suffers from the same problem here as your window.onload did, it calls setTimeout(undefined, 10000);, but executes the request immediately. I also think you mean to call it with the same strName as it was called with.

Your timeout set should say:

setTimeout(function() {show_data(strName);}, 10000); 

A side note - setInterval() and setTimeout() both allow passing strings that get eval()ed at runtime, but I would suggest against using that method which looks like this:

// please dont use me
setTimeout("show_data(strname)", 10000);

At this point your code should work when edited with those two lines. The rest of this stuff is just other optimizations

setTimeout() vs. setInterval()

This seems like it is going to keep checking every 10000ms, unless the ajax request fails, then it will stop. I imagine you just wanted to poll forever. setInterval() allows you to setup a "repeating" timer.

Remove your setTimeout line and replace window.onload with:

var updateInterval;
window.onload = function(){ 
  updateInterval = setInterval(function(){ show_data('Dev'); }, 10000);
};

// an example - lets stop polling 35 seconds from now
setTimeout(function() {
 clearInterval(updateInterval);
}, 35000);