matox
matox

Reputation: 987

Hide spinner if ajax call time below 1 sec

I want to hide spinner for all ajax calls which takes less then 1 second for reply from server.

My current code is

$(window).ready(function(){
  $('#main_wrapper').css({overflow:'hidden'}).append('<div class="splash" style="position: absolute; top: 0; right: 0; bottom:0; left: 0; z-index: 9999; background: #0096d6;"><div id="spinner" style="position: absolute; width: 44px; height: 44px; top: 50%; margin-top: -22px; left: 50%; margin-left: -22px;"></div></div>' ).appendTo('#main_wrapper');
  startSpinner();

  $('#main_wrapper').ajaxStart(function () {
      $('body').css({overflow:'hidden'}).append('<div class="splash" style="position: absolute; top: 0; right: 0; bottom:0; left: 0; z-index: 9999; background: rgba(0,0,0,0);"><div id="spinner" style="position: absolute; width: 44px; height: 44px; top: 50%; margin-top: -22px; left: 50%; margin-left: -22px; z-index: 10000;"></div></div>' ).appendTo( 'body');
      startSpinner("#145A8C");
      $(".splash").hide().delay(1000).show();
  }).ajaxStop(function () {
      $('.splash').fadeOut(300);
      $('.splash').remove();
  });
});

I tried with

 $(".splash").hide().delay(1000).show();

but it doesnt seem to work well.

Any idea?

Upvotes: 0

Views: 340

Answers (1)

Zerragon
Zerragon

Reputation: 26

I recently encountered the same problem, and I solved it by only adding the spinner if the ajax request takes more than 1 second. So your code should look something like:

var timer;
$(document).on({
    ajaxStart: function() {
        timer && clearTimeout(timer);
        timer = setTimeout(function() {
            startSpinner("#145A8C");
            $(".splash").show();
        }, 1000);
    },
    ajaxStop: function() {
        $('.splash').fadeOut(300);
        $('.splash').remove();
        clearTimeout(timer);
    }
}

Upvotes: 1

Related Questions