Only execute code if an AJAX request takes a certain amount of time?

In my web application, I use the $.ajax() request to load data from a database and display it in a browser. During query execution, I display a Loading Results ... message similar to this:

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

It works great. However, if you do not load so much data, the query takes only a fraction of a second. In this case, the message is displayed only for a split second. This animation happens so fast that it is hard to recognize. Therefore, it would be great if it were possible to display the message only if the request took a certain amount of time, that is, a few seconds, at least, but not only a fraction of a second. Is it possible somehow? By the way, I use Django on the server side, if that matters.

+4
source share
2 answers

Use setTimeout to set the timer, cancel the timer when the request is complete:

 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

+8
source

I am with @chris on this solution. But it may also be worth your while to look at http://api.jquery.com/jQuery.ajaxSetup/

This will ensure that you do not have to write a timeout for each individual request.

0
source

All Articles