Skip to content

Commit

Permalink
feat(progress): add throttle for progress events;
Browse files Browse the repository at this point in the history
  • Loading branch information
DigitalBrainJS committed Apr 28, 2024
1 parent f4b9f16 commit d01386e
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 7 deletions.
2 changes: 1 addition & 1 deletion lib/helpers/AxiosTransformStream.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class AxiosTransformStream extends stream.Transform{
}, internals.ticksRate);

const onFinish = () => {
internals.updateProgress(true);
internals.updateProgress.call(true);
};

this.once('end', onFinish);
Expand Down
7 changes: 4 additions & 3 deletions lib/helpers/progressEventReducer.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import speedometer from "./speedometer.js";
import throttle from "./throttle.js";

export default (listener, isDownloadStream) => {
export default (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);

return e => {
return throttle(e => {
const loaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const progressBytes = loaded - bytesNotified;
Expand All @@ -27,5 +28,5 @@ export default (listener, isDownloadStream) => {
data[isDownloadStream ? 'download' : 'upload'] = true;

listener(data);
};
}, freq);
}
8 changes: 5 additions & 3 deletions lib/helpers/throttle.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,23 @@ function throttle(fn, freq) {
let timestamp = 0;
const threshold = 1000 / freq;
let timer = null;
return function throttled(force, args) {
return function throttled() {
const force = this === true;

const now = Date.now();
if (force || now - timestamp > threshold) {
if (timer) {
clearTimeout(timer);
timer = null;
}
timestamp = now;
return fn.apply(null, args);
return fn.apply(null, arguments);
}
if (!timer) {
timer = setTimeout(() => {
timer = null;
timestamp = Date.now();
return fn.apply(null, args);
return fn.apply(null, arguments);
}, threshold - (now - timestamp));
}
};
Expand Down

0 comments on commit d01386e

Please sign in to comment.