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
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
}
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
});
_.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With