[英]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.