Friday, April 29, 2011

Why is my setTimeout() call not working?

Anyone know what's going wrong with below code? The system will only call the getProgressMsg() after the Ajax is completed :(

function ajax_action(action)
{
    setTimeout('getProgressMsg()',2000);

    xmlHttp=GetXmlHttpObject();

    if (xmlHttp==null)
    {
     alert ("Browser does not support HTTP Request")
     return
    }

    var url="admin.php"
    url=url+"?action=admin"
    url=url+"&sid="+Math.random()

    xmlHttp.onreadystatechange=stateChanged;

    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);

}


function getProgressMsg()
{
    xmlHttp2=GetXmlHttpObject2();

    if (xmlHttp2==null)
    {
     alert ("Browser does not support HTTP Request")
     return
    }

    var url2="admin.php"
    url2=url2+"?action=getMsg"
    url2=url2+"&sid="+Math.random()

    xmlHttp2.onreadystatechange=stateChanged2;
    xmlHttp2.open("GET",url2,true);
    xmlHttp2.send(null);
}
From stackoverflow
  • Some thoughts...

    1. You have a two-second timeout. Are you positive the first AJAX request is taking longer than that?
    2. All JavaScript - including event handlers - are single-threaded. If you're busy in stateChanged(), then getProgressMsg() won't be called until you return.
    3. You're doing nothing in getProgressMsg() beyond making another AJAX request - are you sure that's not just being queued up by the browser or the web server to where it won't finish processing 'till the first one completes?

    Suggestions:

    • Try replacing the code in getProgressMsg() with a simple call to alert(). Then reduce the delay from 2000 to 200, and see if it doesn't show up immediately.
    • Verify that you aren't doing any exceptionally heavy processing in stateChanged().
    • Check your server-side code... Verify that you're not holding onto a resource while processing the first request that is needed for processing the second.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.