From 6ac8ee463fc92aa8779143824e80b2bd85ce246d Mon Sep 17 00:00:00 2001 From: Micooz Date: Thu, 5 Jul 2018 18:28:16 +0800 Subject: [PATCH] utils: refactor speed-tester.js --- src/utils/speed-tester.js | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/utils/speed-tester.js b/src/utils/speed-tester.js index a4270a8..5d2bf2e 100644 --- a/src/utils/speed-tester.js +++ b/src/utils/speed-tester.js @@ -1,11 +1,17 @@ export class SpeedTester { - totalBytes = 0; + _totalBytes = 0; - lastTime = Date.now(); + _lastTime = Date.now(); + _lastSpeed = 0; + + /** + * put some bytes to measure later + * @param bytes + */ feed(bytes) { - this.totalBytes += bytes; + this._totalBytes += bytes; } /** @@ -14,11 +20,16 @@ export class SpeedTester { */ getSpeed() { const now = Date.now(); - const timeDiff = now - this.lastTime; - const speed = this.totalBytes / (timeDiff / 1e3); - this.lastTime = now; - this.totalBytes = 0; - return speed; + const timeDiff = now - this._lastTime; + if (timeDiff > 0) { + const speed = this._totalBytes / (timeDiff / 1e3); + this._lastTime = now; + this._lastSpeed = speed; + this._totalBytes = 0; + return speed; + } else { + return this._lastSpeed; + } } }