显示“loading"只有当AJAX调用耗时超过500毫秒时才使用

Show "loading" box only if AJAX call takes more than 500 milliseconds

本文关键字:500毫 调用 AJAX loading quot 显示      更新时间:2023-09-26

我试图使,当一个AJAX请求需要超过500毫秒,"加载"div显示。当请求完成后,div再次被隐藏。

我使用的代码如下。它应该起作用,但它没有。为什么呢?

var timer;
$(document).on({
    ajaxStart: function () {
        timer && clearTimeout(timer);
        timer = setTimeout(function () {
            $('#loading').show();
        }, 500);
    },
    ajaxStop: function () {
        clearTimeout(timer);
        $('#loading').hide();
    }
});

我建议您使用这些方法的文档用法,而不是on()。这些是ajax事件,不是dom事件

$(document).ajaxStart( function () {
        timer && clearTimeout(timer);
        timer = setTimeout(function () {
            $('#processing').show();
        }, 500);
}).ajaxStop( function () {
        clearTimeout(timer);
        $('#processing').hide();       
});

参考:$.ajaxStart() docs

如果您仍然有问题,请深入分析两个事件触发时间的差异

对我来说,你的代码工作得很好:

$(function() {
  var timer, d;
  $('#processing').hide();
  
  $(document).on({
    ajaxStart: function() {
      console.log('started');
      d = performance.now();
      clearTimeout(timer);
      timer = setTimeout(function() {
        $('#processing').show();
      }, 300);
    },
    ajaxStop: function() {
      console.log('finished in ' + (performance.now() - d));
      clearTimeout(timer);
      $('#processing').hide();
    }
  });
  
  $('#load').on('click', function(e) {
    $.get('https://api.github.com/repos/joyent/node/issues?state=closed').then(function(res) {
      $('#result').html('<pre>' + JSON.stringify(res, null, 2) + '</pre>');
    });
  });
  
  $('#load2').on('click', function(e) {
    $.get('https://api.github.com/repos/twbs/bootstrap/issues?state=closed').then(function(res) {
      $('#result').html('<pre>' + JSON.stringify(res, null, 2) + '</pre>');
    });
  });
  
  $('#load3').on('click', function(e) {
    $.get('https://api.github.com/users/buzinas').then(function(res) {
      $('#result').html('<pre>' + JSON.stringify(res, null, 2) + '</pre>');
    });
  });
  
  $('#clear').on('click', function(e) {
    $('#result').html('');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='load'>Load node.js closed issues</button><button id='load2'>Load Bootstrap closed issues</button><button id='load3'>Load Buzina's Github Profile</button><button id='clear'>Clear resuts</button>
<img id='processing' width="16" height="16" alt="star" src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7">
<div id="result"></div>

第一次尝试加载库时,它将花费超过300ms,并且将显示图像。第二次,它们将被浏览器缓存,并且将占用少于300ms的时间,而图像则不会。你可以看到控制台发生了什么。

可能,在你第一次尝试加载我的个人资料时,它将花费不到300ms,并且图像也不会显示。

注意:我已经更改为300ms仅用于测试目的,因为也许更快的连接不会花费500ms来加载Github api。