ajax"忙"指示符,但仅适用于较长的请求

kam*_*mil 2 javascript jquery

是否可以指定时间,之后我可以显示忙碌指示符?

繁忙指标的代码非常简单:

jQuery.ajaxSetup( {
    beforeSend:function ()
    {
        jQuery( "#busy-indicator" ).show();
    }, complete:function ()
    {
        jQuery( "#busy-indicator" ).hide();
    }
} );
Run Code Online (Sandbox Code Playgroud)

但是经常Ajax请求比出现指示器更快,因此我想显示它的请求,至少1秒钟,这可能吗?或者你知道怎么做吗?

alb*_*jan 7

这样做的诀窍:

var timeout; 
jQuery.ajaxSetup( {
    beforeSend:function ()
    {
        if (timeout) { clearTimeout(timeout); }
        timeout = setTimeout(function() {
            jQuery( "#busy-indicator" ).show(); 
        }, 1000);
    }, 
    complete:function ()
    {
        if (timeout) { clearTimeout(timeout); } 
        jQuery( "#busy-indicator" ).hide();
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 经过一些测试后我会添加到你的代码中:`if(timeout){clearTimeout(timeout); 也`在beforeSend的开头,连续2次ajax请求搞砸了一点超时:) (2认同)