[英]Wait before showing a loading spinner?
我想在我的单页Web应用程序中使用加载微调器,如果您希望在请求被触发后立即显示微调器并在请求完成后立即隐藏它,这很容易。
由于请求通常只需要几百毫秒或更短的时间才能完成,我宁愿不立即显示一个微调器,而是先等待X毫秒,以便在那些花费不到X毫秒的请求完成时,微调器不会t闪烁在屏幕上并消失,这可能是刺耳的,特别是在多个面板一次加载数据的时候。
我的第一直觉是使用setTimeout,但我无法弄清楚如何取消多个计时器中的一个。
我是否必须创建一个Timer类,以便我可以停止并启动类似setTimeout的对象的不同实例? 我是从错误的角度思考这个问题的吗?
var timer = setTimeout(function () {
startSpinner();
}, 2000);
然后在你的回调中你可以把:
clearTimeout(timer);
stopSpinner();
你可以在一些Timer
类(我做过)中包装setTimout
和clearTimeout
但你不需要:)
创建你的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
演示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.