File size: 1,866 Bytes
b797337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
class Timer {

	constructor() {

		this._previousTime = 0;
		this._currentTime = 0;
		this._startTime = now();

		this._delta = 0;
		this._elapsed = 0;

		this._timescale = 1;

		// use Page Visibility API to avoid large time delta values

		this._usePageVisibilityAPI = ( typeof document !== 'undefined' && document.hidden !== undefined );

		if ( this._usePageVisibilityAPI === true ) {

			this._pageVisibilityHandler = handleVisibilityChange.bind( this );

			document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );

		}

	}

	getDelta() {

		return this._delta / 1000;

	}

	getElapsed() {

		return this._elapsed / 1000;

	}

	getTimescale() {

		return this._timescale;

	}

	setTimescale( timescale ) {

		this._timescale = timescale;

		return this;

	}

	reset() {

		this._currentTime = now() - this._startTime;

		return this;

	}

	dispose() {

		if ( this._usePageVisibilityAPI === true ) {

			document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );

		}

		return this;

	}

	update( timestamp ) {

		this._previousTime = this._currentTime;
		this._currentTime = ( timestamp !== undefined ? timestamp : now() ) - this._startTime;

		this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
		this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas

		return this;

	}

}

class FixedTimer extends Timer {

	constructor( fps = 60 ) {

		super();
		this._delta = ( 1 / fps ) * 1000;

	}

	update() {

		this._elapsed += ( this._delta * this._timescale ); // _elapsed is the accumulation of all previous deltas

		return this;

	}

}

function now() {

	return ( typeof performance === 'undefined' ? Date : performance ).now();

}

function handleVisibilityChange() {

	if ( document.hidden === false ) this.reset();

}

export { Timer, FixedTimer };