Skip to content

Commit

Permalink
Support read with units
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonray authored Nov 18, 2023
2 parents 59d513a + 3620e96 commit 5780d3e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/Stopwatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ Stopwatch.prototype.start = function () {

self._verifyState([STATES.STOPPED, STATES.INIT], "Cannot start a stopwatch that is currently running");

self.reset();
self._state = STATES.RUNNING;
self.startTime = now();
self.stopTime = 0;
};

Stopwatch.prototype.stop = function () {
Expand Down Expand Up @@ -131,7 +131,7 @@ Stopwatch.prototype.splitTime = function () {
return self._calculateDelta(self.startTime, self.stopTime);
};

Stopwatch.prototype.read = Stopwatch.prototype.time = function (precision) {
Stopwatch.prototype.read = Stopwatch.prototype.time = function (precision, units) {
const self = this;
const startTime = self.startTime;
let delta = null;
Expand All @@ -150,6 +150,11 @@ Stopwatch.prototype.read = Stopwatch.prototype.time = function (precision) {
delta = delta + self._StartTimeDelta;
}

// is in `ms` by default
if (units === "s") {
delta = delta / 1000;
}

if (precision || precision === 0) {
delta = delta.toFixed(precision);
}
Expand Down
15 changes: 15 additions & 0 deletions test/stopwatch-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,21 @@ describe("stopwatch", function () {
}, testtime);
});

it("read with units", function (done) {
const timeMs = 2000;
const timeS = 2;

const stopwatch = new Stopwatch();
stopwatch.start();
setTimeout(function () {
const delta = stopwatch.read("s");
verifyDelta(timeMs, stopwatch.read(1,"ms"), defaultPrecision);
verifyDelta(timeS, stopwatch.read(1,"s"), defaultPrecision);
done();
}, timeMs);
});


describe("suspend / resume", function () {
it("unable to suspend a new stopwatch", function () {
const stopwatch = new Stopwatch();
Expand Down

0 comments on commit 5780d3e

Please sign in to comment.