简体   繁体   English

在显示加载微调器之前等待?

[英]Wait before showing a loading spinner?

I want to use loading spinners in my single-page web application, which are easy enough to do if you want to show a spinner as soon as the request is fired and hide it as soon as the request is finished. 我想在我的单页Web应用程序中使用加载微调器,如果您希望在请求被触发后立即显示微调器并在请求完成后立即隐藏它,这很容易。

Since requests often only take a few hundred milliseconds or less to complete, I'd rather not show a spinner right away, but rather wait X milliseconds first so that, on those requests that take less than X milliseconds to complete, the spinner doesn't flash on the screen and disappear, which could be jarring, especially in times when multiple panels are loading data at once. 由于请求通常只需要几百毫秒或更短的时间才能完成,我宁愿不立即显示一个微调器,而是先等待X毫秒,以便在那些花费不到X毫秒的请求完成时,微调器不会t闪烁在屏幕上并消失,这可能是刺耳的,特别是在多个面板一次加载数据的时候。

My first instinct is to use setTimeout, but I'm having trouble figuring out how to cancel one of multiple timers. 我的第一直觉是使用setTimeout,但我无法弄清楚如何取消多个计时器中的一个。

Would I have to create a Timer class so that I could stop and start different instances of a setTimeout-like object? 我是否必须创建一个Timer类,以便我可以停止并启动类似setTimeout的对象的不同实例? Am I thinking about this from the wrong angle? 我是从错误的角度思考这个问题的吗?

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

Then in your callback you can put: 然后在你的回调中你可以把:

clearTimeout(timer);
stopSpinner();

You could wrap setTimout and clearTimeout in some Timer class (I did) but you don't need to :) 你可以在一些Timer类(我做过)中包装setTimoutclearTimeout但你不需要:)

Create your jquery function: 创建你的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);

Usage: 用法:

$('#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

Demo: 演示:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM