Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code only if AJAX request takes a certain amount of time?

In my web application, I'm using an $.ajax() request to load data from a database and display it in the browser. During the execution of the request, I display a Loading Results ... message like this:

$.ajax({
    // ...
    beforeSend: function() {
        $('#loading-results-message').show();
    },
    complete: function() {
        $('#loading-results-message').hide(); 
    }
});

This works fine. However, if there is not much data to load, the request takes only a fraction of a second. In this case, the message is only displayed for a fraction of a second as well. This animation happens so quickly that it's difficult to recognize it. Therefore, it would be great if it was possible to display the message only if the request takes a certain amount of time, i.e. some seconds at least but not only a fraction of a second. Is that possible somehow? By the way, I'm using Django on the server side, if that should matter.

like image 316
pemistahl Avatar asked Feb 17 '23 12:02

pemistahl


1 Answers

Use setTimeout to establish a timer, cancel the timer when the request completes:

var desired_delay = 2000;
var message_timer = false;
$.ajax({
    // ...
    beforeSend: function() {
        message_timer = setTimeout(function () {
            $('#loading-results-message').show();
            message_timer = false;
        }, desired_delay);
    },
    complete: function() {
        if (message_timer)
            clearTimeout(message_timer);
        message_timer = false;
        $('#loading-results-message').hide(); 
    }
});

Documentation

  • setTimeout on MDN - https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout
  • clearTimeout on MDN - https://developer.mozilla.org/en-US/docs/DOM/window.clearTimeout
like image 122
Chris Baker Avatar answered Feb 20 '23 04:02

Chris Baker