123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222 |
- class Timer {
-
- constructor() {
- this._previousTime = 0;
- this._currentTime = 0;
- this._startTime = now();
- this._delta = 0;
- this._elapsed = 0;
- this._timescale = 1;
- this._document = null;
- this._pageVisibilityHandler = null;
- }
-
- connect( document ) {
- this._document = document;
-
- if ( document.hidden !== undefined ) {
- this._pageVisibilityHandler = handleVisibilityChange.bind( this );
- document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
- }
- }
-
- disconnect() {
- if ( this._pageVisibilityHandler !== null ) {
- this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
- this._pageVisibilityHandler = null;
- }
- this._document = null;
- }
-
- 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() {
- this.disconnect();
- }
-
- update( timestamp ) {
- if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
- this._delta = 0;
- } else {
- this._previousTime = this._currentTime;
- this._currentTime = ( timestamp !== undefined ? timestamp : now() ) - this._startTime;
- this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
- this._elapsed += this._delta;
- }
- return this;
- }
- }
- class FixedTimer extends Timer {
-
- constructor( fps = 60 ) {
- super();
- this._delta = ( 1 / fps ) * 1000;
- }
- update() {
- this._elapsed += ( this._delta * this._timescale );
- return this;
- }
- }
- function now() {
- return performance.now();
- }
- function handleVisibilityChange() {
- if ( this._document.hidden === false ) this.reset();
- }
- export { Timer, FixedTimer };
|