Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How often does xhr.upload.onProgress fire?

I am subscribing to the onProgress event when uploading a file via XHR. My progress bar is animated (via jQuery) to provide a better visual aesthetic.

onProgress seems to fire very rapidly, so I wondered how often it actually gets fired so that I can somehow devise a process whereby I can throttle responses to this so that I can have one continuously animated progress bar

like image 483
Chris Avatar asked Jul 21 '11 13:07

Chris


3 Answers

While extending jQuery can be beneficial; for something this simple extending jQuery is not worth the overhead. An effective solution for limiting function calls could be written as:

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
}
like image 193
Caleb Gray Avatar answered Nov 14 '22 14:11

Caleb Gray


Check out the jQuery throttle/debounce plugin for throttling the calls to your onprogress callback.

Throttling demos: http://benalman.com/code/projects/jquery-throttle-debounce/examples/throttle/

Your code would look something like this:

xhr.upload.onprogress = $.throttle(100, function (event)
{
    // update the progress bar
});
like image 43
Matt Ball Avatar answered Nov 14 '22 13:11

Matt Ball


_.throttle(function, wait)

UnderscoreJS has utilities for throttling functions.

The actual amount onProgress get's fired is browser specific so it's best to throttle the actual callback on a time-based solution.

like image 25
Raynos Avatar answered Nov 14 '22 15:11

Raynos