2013-01-18 45 views
1

我想在我的单页web应用程序中使用加载纺纱器,如果您希望在请求被触发时立即显示微调,并且一旦请求完成就立即隐藏,这很容易实现。等待显示加载微调器之前?

由于请求往往只需要几百毫秒以内完成,我宁愿没有表现出微调的时候了,而是先等待X毫秒,这样,对那些需要小于X毫秒的请求完成后,旋转器不会在屏幕上闪烁并消失,这可能会震动,特别是在多个面板一次加载数据的时候。

我的第一本能是使用setTimeout,但我无法弄清楚如何取消多个定时器之一。

我需要创建一个Timer类,以便我可以停止并启动setTimeout类对象的不同实例吗?我从错误的角度思考这个问题吗?

+0

'setTimeout'返回定时器的ID。然后,您将该ID传递给'clearTimeout'。 –

回答

1
var timer = setTimeout(function() { 
    startSpinner(); 
}, 2000); 

然后在你的回调,你可以把:

clearTimeout(timer); 
stopSpinner(); 

你可以在一些Timer类(我做了)包裹setTimoutclearTimeout但你并不需要:)

+0

+1击败我吧! dang –

+1

-1不适用于多个纺纱厂 – Peter

+0

很容易修改多个纺纱厂。你可以用多种方式实现它。您可以简单地将spinners都放在'startSpinner'函数中。因为你为什么会有不同超时的微调?从用户体验角度来看,这很奇怪。如果纺纱厂处于不同的“小部件”,那么他们不应该由相同的代码控制。 – Halcyon

2

创建您的jquery功能:

(function ($) { 
    function getTimer(obj) { 
    return obj.data('swd_timer'); 
    } 

    function setTimer(obj, timer) { 
    obj.data('swd_timer', timer); 
    } 

    $.fn.showWithDelay = function (delay) { 
    var self = this; 
    if (getTimer(this)) { 
     window.clearTimeout(getTimer(this)); // prevents duplicate timers 
    } 
    setTimer(this, window.setTimeout(function() { 
     setTimer(self, false); 
     $(self).show(); 
    }, delay)); 
    }; 
    $.fn.hideWithDelay = function() { 

    if (getTimer(this)) { 
     window.clearTimeout(getTimer(this)); 
     setTimer(this, false); 
    } 
    $(this).hide(); 
    } 
})(jQuery); 

用法:

$('#spinner').showWithDelay(100); // fire it when loading. spinner will pop up in 100 ms 
$('#spinner').hideWithDelay(); // fire it when loading is finished 
            // if executed in less than 100ms spinner won't pop up 

演示:

相关问题