How to invoke a “Please Wait” window only if ajax takes more than X milliseconds to respond?

半城伤御伤魂 提交于 2019-11-28 02:23:53

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 helper
function req(url, callback) {
  var xhr = new XMLHttpRequest();
  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 stuff
  alert(xhr.responseText);
});

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

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.

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

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

Take a Look at jQuery Timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!