Skip to content Skip to sidebar Skip to footer

How To Invoke A "please Wait" Window Only If Ajax Takes More Than X Milliseconds To Respond?

I'm doing an AJAX call (regular JS) and, if it takes more than, say, 500 milliseconds, I'd like to put up my 'Please Wait' box. Normally, if I want to put up the PW box immediately

Solution 1:

Given that you are making a synchronous XHR call, you can't. That's the nature of synchronouseverything stops until the call completes. When you use a synchronous XHR request, not only is the JavaScript event loop stopped, you actually freeze the entire browser UI (in IE and Firefox < 3).

That said, you're doing it wrong. 8.4% of reported IE9 hangs last month were due to synchronous XHR. There really is no such thing as ‘an unusual situation that requires use of synchronous XHR requests.’ Make your request, then act on the data you get in the callback function.

Instead of something like:

// Do stuff, then when you need a request:var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send();
// Do more stuff
alert(xhr.responseText);

You need:

// AJAX helperfunctionreq(url, callback) {
  var xhr = newXMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) callback(xhr);
  }
}


// Your code.  Do stuff, then when you need an AJAX request:req(url, function(xhr) {
  // Do more stuffalert(xhr.responseText);
});

Obviously this needs refined, but this illustrates the proper way to make an AJAX request.

Solution 2:

It shouldn't come after the ajax call, it should come inside the callback function. AJAX requests are asynchronous with the rest of the code, you should preform actions you want upon completion inside the callback part of your request.

Solution 3:

take a look at BlockUi. If that doesn't look like it will work for you, you could try using

$(document).ajaxStop(DoSomething()); 

Solution 4:

Take a Look at jQuery Timeout

Post a Comment for "How To Invoke A "please Wait" Window Only If Ajax Takes More Than X Milliseconds To Respond?"