简体   繁体   中英

time an ajax request

Is there any way to time how long a jquery ajax request has been going on? sometimes searches take too long and it would be nice to add a jquery abort() button if the search takes over, say, 5 seconds. Any way I can do this!

On the other end of the ajax request is a php file that makes a postgresql request.

Much thanks for any ideas!

Take a look at the timeout option (http://api.jquery.com/jQuery.ajax/). You can set it on a particular call, or globally with $.ajaxSetup().

To have the abort button appear after 5 seconds, add a setTimeout function after your call to send . Once the AJAX command is complete, you can add code to clear the timeout and remove the abort button if it exists.

var timeOutID = 0;
$.ajax({
  url: 'ajax/test.html',
  success: function(data) {     
    clearTimeOut(timeOutID);
    // Remove the abort button if it exists.
  }
});
timeOutID = setTimeout(function() {
                 // Add the abort button here.
               }, 5000);   

This way the abort button will never appear if AJAX returns quick enough.

Usually, I'll set a timeout once the request is sent that will trigger after 10 seconds or so and then fallback on something else to make sure it still happens (for example, form submission).

So set a variable to false, var failed = false; and do the request At the same time that the request starts, set a timeout:

setTimeout(function() {
    failed = true;
    $("#form").submit();
    return false;
}, 10000);

In the return function of the ajax call, check to see if the failed variable has been set to true, and if it has, don't actually do whatever it was originally trying, otherwise it could mess something up, or confuse the user if something else is happening (since these things usually happen on slower internet connections, if the next step appears while a new page is loading, they might try to interact and then the page will change).

$.post("ajaxcall.php", {'etc': "etc"},
    function(returned) {
        if (failed != true) {
            //do whatever with returned variable
        }
});
var timer = 0,
    XHR = $.ajax({
             url: 'ajax/mypage.html',
             beforeSend: function() {
                 timer=setTimeout(showAbort, 5000);
             }
          });

function showAbort() {
    $('<input type="button" value="Abort" id="abort_button"/>').appendTo('#some_parent');
    $('#abort_button').on('click', function() {
         XHR.abort(); //abort the Ajax call
    });
}

XHR.always(function() {  //fires on both fail and done
    clearTimeout(timer);
    if ($('#abort_button').length) {
       $('#abort_button').remove(); //remove button if exists
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM