Is it possible to show the "Loading.." animation only if the ajax call takes more than say, one second? Some of my ajax calls are pretty fast but I still see the loading icon for a fraction of a second before it disappears. May be it's just me, but I find it distracting. I don't want to remove it altogether though. Any suggestions? Here's my code -
$('#loading').hide() .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); }); <div id="loading"> <img alt="Loading, please wait.." src="/content/images/spinner.gif" /> </div>
Creating a function that calls the AJAX request and using this function in setInterval() and set Interval for 5 sec. Now the function executes every 5 seconds and fetches new data from the server. It repeatedly executes the function even when the previous AJAX request is not successfully executed and return.
The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.
success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.
You should put your code in a timer:
var $loader = $('#loading'), timer; $loader.hide() .ajaxStart(function() { timer && clearTimeout(timer); timer = setTimeout(function() { $loader.show(); }, 1000); }) .ajaxStop(function() { clearTimeout(timer); $loader.hide(); });
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