Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - show loading image only if ajax call takes more than one second?

Tags:

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> 
like image 776
tempid Avatar asked Jan 31 '12 04:01

tempid


People also ask

How do you send Ajax request every 5 seconds?

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.

How do I know if Ajax request is successful?

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.

What is difference between success and complete in Ajax?

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.


1 Answers

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();     }); 
like image 103
Joseph Silber Avatar answered Oct 13 '22 06:10

Joseph Silber