Skip to content

Commit 3325e62

Browse files
Merge pull request #372 from RomanBurunkov/master
Optimize upload timer.
2 parents 4313856 + 4cdd94a commit 3325e62

File tree

5 files changed

+348
-209
lines changed

5 files changed

+348
-209
lines changed

lib/processMultipart.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ module.exports = (options, req, res, next) => {
111111
});
112112

113113
file.on('data', (data) => {
114-
uploadTimer.set(); // Refresh upload timer each time new data chunk came.
114+
uploadTimer.refresh(); // Refresh upload timer each time new data chunk came.
115115
dataHandler(data); // Handle new piece of data.
116116
});
117117

lib/uploadtimer.js

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,45 @@
11
class UploadTimer {
22
/**
33
* @constructor
4-
* @param {number} timeout - timer timeout in msecs.
4+
* @param {number} timeout - timer timeout in msecs.
55
* @param {Function} callback - callback to run when timeout reached.
66
*/
7-
constructor(timeout = 0, callback = () => {}) {
8-
this.timeout = timeout;
9-
this.callback = callback;
7+
constructor(timeout, callback) {
8+
this.timeout = timeout || 0;
9+
this.callback = callback || (() => {});
1010
this.timer = null;
1111
}
1212

13+
/**
14+
* Sets the timer.
15+
* Initializes & starts the timer.
16+
* @returns {boolean} True if timer has been set.
17+
*/
18+
set() {
19+
if (this.timer || !this.timeout) return false;
20+
this.timer = setTimeout(() => {
21+
this.clear();
22+
this.callback();
23+
}, this.timeout);
24+
return true;
25+
}
26+
27+
/**
28+
* Clears the timer.
29+
* If timer cleared, it has to be re-initialized again with set method.
30+
*/
1331
clear() {
1432
clearTimeout(this.timer);
1533
}
1634

17-
set() {
18-
// Do not start a timer if zero timeout or it hasn't been set.
19-
if (!this.timeout) return false;
20-
this.clear();
21-
this.timer = setTimeout(this.callback, this.timeout);
35+
/**
36+
* Refreshes timer.
37+
* @returns {boolean} True if timer has been refreshed.
38+
*/
39+
refresh() {
40+
// Do nothing if zero/empty timeout or timer hasn't been initialized.
41+
if (!this.timer) return false;
42+
this.timer.refresh();
2243
return true;
2344
}
2445
}

0 commit comments

Comments
 (0)