Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delay the showing of a ajax loading gif using jQuery

Tags:

jquery

What is the best way to put a delay on the showing of a ajax-loader gif. When I click a button the loader gif shows and hides even if the time taken is a few hundred milli-seconds, this gives the browser a kind of flicker. What I want is to say only show the gif if it takes more than say 1000 milli-seconds to complete the ajax request.

 <script type="text/javascript">
     $(document).ready(function() {
         $('#loader').hide();
         $('#btnGetPeople').click(function() {
            $('#loader').show();
             $.getJSON("/User/GetName/10",
                null,
                function(data) { showPerson(data); });
         });
     });

     function showPerson(data) {
         alert(data);
         $('#loader').hide();
     }
</script>

My loader div contains....

<div id="loader"><img alt="" src="/content/ajax-loader.gif" /></div>

What is the best technique to achieve this?

like image 857
Rippo Avatar asked Dec 05 '09 08:12

Rippo


2 Answers

As you can see I added a timeout which delay showing for 300ms. If ajax is faster the timeout is cancelled before the loader gets really shown.

<script type="text/javascript">
    var showLoader;
    $(document).ready(function() {
        $('#loader').hide();
        $('#btnGetPeople').click(function() {
            // only show loader if ajax request lasts longer then 300 ms
            showLoader = setTimeout("$('#loader').show()", 300);
            $.getJSON("/User/GetName/10",
                null,
                function(data) { showPerson(data); });
        });
    });

    function showPerson(data) {
        clearTimeout(showLoader);
        alert(data);
        $('#loader').hide();
    }
</script>
like image 58
jitter Avatar answered Sep 28 '22 18:09

jitter


Here is a fun way to do it. Replace $loader.show() with this:

$("#loader").data('timeout', window.setTimeout(function(){ $("#loader").show()}, 1000));

And your hide command with this:

window.clearTimeout($("#loader").hide().data('timeout'));
like image 20
Doug Neiner Avatar answered Sep 28 '22 20:09

Doug Neiner