2016-04-18 17:20:30 -04:00
|
|
|
/**
|
2016-09-12 13:09:01 -04:00
|
|
|
* @fileoverview
|
|
|
|
* A utility for accurately measuring time.
|
|
|
|
* To use:
|
|
|
|
* ---
|
|
|
|
* var timer = new Timer();
|
|
|
|
* timer.start();
|
|
|
|
* ... pass some time ...
|
|
|
|
* var timeDifference = timer.timeElapsed();
|
|
|
|
* ---
|
|
|
|
* Or, you can use the `time` and `relativeTime`
|
|
|
|
* to do some measurement yourself.
|
2016-04-18 17:20:30 -04:00
|
|
|
*/
|
|
|
|
|
2016-09-12 13:09:01 -04:00
|
|
|
/**
|
|
|
|
* @constructor
|
|
|
|
*/
|
2016-10-23 17:55:31 -04:00
|
|
|
var Timer = function () {};
|
2016-09-12 13:09:01 -04:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Used to store the start time of a timer action.
|
|
|
|
* Updated when calling `timer.start`.
|
|
|
|
*/
|
|
|
|
Timer.prototype.startTime = 0;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return the currently known absolute time, in ms precision.
|
|
|
|
* @returns {number} ms elapsed since 1 January 1970 00:00:00 UTC.
|
|
|
|
*/
|
2016-04-18 17:20:30 -04:00
|
|
|
Timer.prototype.time = function () {
|
2016-09-12 13:09:01 -04:00
|
|
|
if (Date.now) {
|
|
|
|
return Date.now();
|
|
|
|
} else {
|
|
|
|
return new Date().getTime();
|
|
|
|
}
|
2016-04-18 17:20:30 -04:00
|
|
|
};
|
|
|
|
|
2016-09-12 13:09:01 -04:00
|
|
|
/**
|
|
|
|
* Returns a time accurate relative to other times produced by this function.
|
|
|
|
* If possible, will use sub-millisecond precision.
|
|
|
|
* If not, will use millisecond precision.
|
|
|
|
* Not guaranteed to produce the same absolute values per-system.
|
|
|
|
* @returns {number} ms-scale accurate time relative to other relative times.
|
|
|
|
*/
|
|
|
|
Timer.prototype.relativeTime = function () {
|
|
|
|
if (typeof self !== 'undefined' &&
|
|
|
|
self.performance && 'now' in self.performance) {
|
|
|
|
return self.performance.now();
|
|
|
|
} else {
|
|
|
|
return this.time();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Start a timer for measuring elapsed time,
|
|
|
|
* at the most accurate precision possible.
|
|
|
|
*/
|
2016-04-18 17:20:30 -04:00
|
|
|
Timer.prototype.start = function () {
|
2016-09-12 13:09:01 -04:00
|
|
|
this.startTime = this.relativeTime();
|
2016-04-18 17:20:30 -04:00
|
|
|
};
|
|
|
|
|
2016-09-12 13:09:01 -04:00
|
|
|
/**
|
|
|
|
* Check time elapsed since `timer.start` was called.
|
|
|
|
* @returns {number} Time elapsed, in ms (possibly sub-ms precision).
|
|
|
|
*/
|
2016-04-26 15:00:45 -04:00
|
|
|
Timer.prototype.timeElapsed = function () {
|
2016-09-12 13:09:01 -04:00
|
|
|
return this.relativeTime() - this.startTime;
|
2016-04-18 17:20:30 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = Timer;
|