jQuery – 仅在ajax调用超过一秒时才显示加载图像?

只有当ajax调用超过一秒钟时,是否可以显示“正在加载…”动画? 我的一些ajax调用非常快,但在它消失之前我仍然看到加载图标只有几分之一秒。 可能只是我,但我觉得它让人分心。 我不想完全删除它。 有什么建议? 这是我的代码 –

$('#loading').hide() .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); }); 
Loading, please wait..

你应该把你的代码放在一个计时器中:

 var $loader = $('#loading'), timer; $loader.hide() .ajaxStart(function() { timer && clearTimeout(timer); timer = setTimeout(function() { $loader.show(); }, 1000); }) .ajaxStop(function() { clearTimeout(timer); $loader.hide(); }); 

您可以使用setTimeout()

 var loadingTimeout; $('#loading').hide() .ajaxStart(function() { var element = $(this); loadingTimeout = setTimeout(function() { element.show(); }, 1e3); }) .ajaxStop(function() { clearTimeout(loadingTimeout); $(this).hide(); });