When I have multiple AJAX calls on a webpage, some complete quickly while others take longer depending on the action clicked.
I am looking to implement a "loader" that shows up after a certain number of seconds when AJAX is processing results.
I have managed to get the loader functioning:
$(document).ajaxStart(function() {
$("#loader").css("display","block");
}).ajaxSuccess(function() {
$("#loader").css("display","none");
});
This works fine.
However, it flashes briefly on the screen when the AJAX request is fast, causing a distraction. While the functionality is great, I want to delay the loader's appearance for a few seconds so it doesn't flash unnecessarily.
I tried using setTimeout and jQuery queue to introduce a delay like this:
$(document).ajaxStart(function() {
$("#loader").queue(function(){
$(this).delay(5000);
$(this).css("display","block");
$(this).dequeue();
});
}).ajaxSuccess(function() {
$("#loader").css("display","none");
});
or:
$(document).ajaxStart(function() {
setTimeout(function() {
$("#loader").css("display","block");
}, 5000);
}).ajaxSuccess(function() {
$("#loader").css("display","none");
});
(delaying jquery css changes)
or:
$(document).ajaxStart(function() {
$("#loader").delay(5000).css("display","block")
}).ajaxSuccess(function() {
$("#loader").css("display","none");
});
But the issue I encounter is that any attempt to delay the CSS change on ajax start often results in a delayed appearance... after the AJAX process has finished.
So what happens is that the page loads the AJAX data first and then 5 seconds later, the loader pops up.
Is there a way to instruct the ajaxStart() function to wait for X seconds before executing?
I prefer not to include this delay in the actual AJAX calls using something like onBefore function(), as some results are returned quickly and do not require a progress indicator. In most cases, the progress indicator should not be displayed. Typically, AJAX requests are completed within 5 seconds, with only a few taking longer (10-20 seconds).
I have included the removal of the 'loader' in the complete function() of the AJAX calls to ensure it disappears once the AJAX operation is done. However, this fails if the AJAX completes before the setTimeout() value is reached, resulting in the loader appearing afterwards when it shouldn't.
All I want is a CSS change on an element if the AJAX operation takes X seconds or more...is that achievable?
Is there a method to time something during AJAX requests?