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

tem*_*pid 23 jquery

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

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

<div id="loading">
    <img alt="Loading, please wait.." src="/content/images/spinner.gif" />
</div>
Run Code Online (Sandbox Code Playgroud)

Jos*_*ber 34

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

var $loader = $('#loading'), timer;

$loader.hide()
    .ajaxStart(function()
    {
        timer && clearTimeout(timer);
        timer = setTimeout(function()
        {
            $loader.show();
        },
        1000);
    })
    .ajaxStop(function()
    {
        clearTimeout(timer);
        $loader.hide();
    });
Run Code Online (Sandbox Code Playgroud)

  • @codepuppy - `clearTimeout`需要一个计时器ID作为参数.第一次`ajaxStart`运行时,`timer`将是未定义的.虽然将undefined传递给`clearTimeout`似乎没有引起任何错误,但我还没有测试它,所以我决定首先检查`timer`是否真的有id.Nore表示`timer && clearTimeout(timer);`相当于`if(timer){clearTimeout(timer); }`. (2认同)

ale*_*lex 9

你可以用一个setTimeout().

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