jQuery - show loading image only if ajax call takes more than one second?

前端 未结 2 378
终归单人心
终归单人心 2020-12-12 19:43

Is it possible to show the \"Loading..\" animation only if the ajax call takes more than say, one second? Some of my ajax calls are pretty fast but I still see the loading i

相关标签:
2条回答
  • 2020-12-12 20:18

    You should put your code in a timer:

    var $loader = $('#loading'), timer;
    
    $loader.hide()
        .ajaxStart(function()
        {
            timer && clearTimeout(timer);
            timer = setTimeout(function()
            {
                $loader.show();
            },
            1000);
        })
        .ajaxStop(function()
        {
            clearTimeout(timer);
            $loader.hide();
        });
    
    0 讨论(0)
  • 2020-12-12 20:27

    You could use a setTimeout().

    var loadingTimeout;
    $('#loading').hide()
    .ajaxStart(function() {
        var element = $(this);
        loadingTimeout = setTimeout(function() {
           element.show();
        }, 1e3);
    })
    .ajaxStop(function() {
        clearTimeout(loadingTimeout);
        $(this).hide();
    });
    
    0 讨论(0)
提交回复
热议问题