如果ajax调用时间低于1秒,则隐藏微调器

时间:2014-10-28 08:48:43

标签: javascript jquery ajax spinner

我想隐藏所有ajax调用的微调器,从服务器回复需要不到1秒。

我目前的代码是

$(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();
  });
});

我试过

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

但似乎效果不好。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我最近遇到了同样的问题,如果ajax请求超过1秒,我只通过添加微调器来解决它。因此,您的代码应该类似于:

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);
    }
}