【问题标题】:How often does xhr.upload.onProgress fire?xhr.upload.onProgress 多久触发一次?
【发布时间】:2011-10-10 06:12:13
【问题描述】:

通过 XHR 上传文件时,我正在订阅 onProgress 事件。我的进度条是动画的(通过 jQuery),以提供更好的视觉美感。

onProgress 似乎触发得非常快,所以我想知道它实际触发的频率是多少,以便我可以以某种方式设计一个流程,借此我可以限制对此的响应,这样我就可以拥有一个连续动画进度条

【问题讨论】:

    标签: jquery html xmlhttprequest


    【解决方案1】:

    虽然扩展 jQuery 可能是有益的;对于这个简单的扩展 jQuery 的东西来说,开销是不值得的。限制函数调用的有效解决方案可以写成:

    xhr.upload.onprogress = function(event) {
      // limit calls to this function
      if (!this.NextSecond) this.NextSecond = 0;
      if (Date.getTime() < this.NextSecond) return;
      this.NextSecond = Date.getTime() + 1000;
    
      // this code gets executed at least one second apart from the last time
    }
    

    【讨论】:

      【解决方案2】:

      查看jQuery throttle/debounce plugin 以限制对onprogress 回调的调用。

      节流演示:http://benalman.com/code/projects/jquery-throttle-debounce/examples/throttle/

      您的代码将如下所示:

      xhr.upload.onprogress = $.throttle(100, function (event)
      {
          // update the progress bar
      });
      

      【讨论】:

        【解决方案3】:

        _.throttle(function, wait)

        UnderscoreJS 具有用于节流功能的实用程序。

        onProgress 触发的实际数量是特定于浏览器的,因此最好在基于时间的解决方案中限制实际回调。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-02-26
          • 2019-03-12
          • 1970-01-01
          • 1970-01-01
          • 2016-12-23
          • 1970-01-01
          • 1970-01-01
          • 2015-10-20
          相关资源
          最近更新 更多