Alex Rivera | Logout

Delaying the loading spinner while doing ajax requests in jQuery

Asked 2012-03-13T20:33:13.947
12

I'm using the following mockup to show my loading spinner while doing AJAX requests in my jQuery code:

jQuery.ajaxSetup({
beforeSend: function() {
    $('#loader').show()
},
complete: function(){
    $('#loader').hide()
},
success: function() {
    $('#loader').hide()
}
});

This code works perfectly fine for me!

Just one problem:

Some requests are just very simple and fast, so the loading spinner is just shown for a couple of millisecs. That of course isn't very pretty.

So I tried using setTimeout() to display the loading spinner slightly delayed. I want it to only pop up if the AJAX requests takes at least, let's say 100ms, but it didn't work.

So I need some code to delay the loading spinner as I explained above, so it ONLY pops up while doing "longer" AJAX requests!

Edit
Report

1 Answer

0

This should work:

var timeout;

jQuery.ajaxSetup({
beforeSend: function() {
    timeout = window.setTimeout(function() {
        timeout = null;
        $('#loader').show();
    }, 100);
},
complete: function(){
    if (timeout) {
        window.clearTimeout(timeout);
        timeout = null;
    }
    $('#loader').hide()
},
success: function() {
    // No need to do anything here since complete always will be called
}
});

Now you need to improve this a bit if you are firing several request at the same time, but hopefully you get the picture.

answered 2012-03-13T20:44:31.460

Your Answer