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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With