forked from scratchfoundation/scratch-vm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.js
More file actions
89 lines (80 loc) · 2.42 KB
/
Copy pathtimer.js
File metadata and controls
89 lines (80 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* @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.
*/
class Timer {
constructor () {
/**
* Used to store the start time of a timer action.
* Updated when calling `timer.start`.
*/
this.startTime = 0;
}
/**
* Disable use of self.performance for now as it results in lower performance
* However, instancing it like below (caching the self.performance to a local variable) negates most of the issues.
* @type {boolean}
*/
static get USE_PERFORMANCE () {
return false;
}
/**
* Legacy object to allow for us to call now to get the old style date time (for backwards compatibility)
* @deprecated This is only called via the nowObj.now() if no other means is possible...
*/
static get legacyDateCode () {
return {
now: function () {
return new Date().getTime();
}
};
}
/**
* Use this object to route all time functions through single access points.
*/
static get nowObj () {
if (Timer.USE_PERFORMANCE && typeof self !== 'undefined' && self.performance && 'now' in self.performance) {
return self.performance;
} else if (Date.now) {
return Date;
}
return Timer.legacyDateCode;
}
/**
* Return the currently known absolute time, in ms precision.
* @returns {number} ms elapsed since 1 January 1970 00:00:00 UTC.
*/
time () {
return Timer.nowObj.now();
}
/**
* 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.
*/
relativeTime () {
return Timer.nowObj.now();
}
/**
* Start a timer for measuring elapsed time,
* at the most accurate precision possible.
*/
start () {
this.startTime = Timer.nowObj.now();
}
timeElapsed () {
return Timer.nowObj.now() - this.startTime;
}
}
module.exports = Timer;