123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- /**
- * Class for keeping track of time.
- */
- class Clock {
- /**
- * Constructs a new clock.
- *
- * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
- * `getDelta()` is called for the first time.
- */
- constructor( autoStart = true ) {
- /**
- * If set to `true`, the clock starts automatically when `getDelta()` is called
- * for the first time.
- *
- * @type {boolean}
- * @default true
- */
- this.autoStart = autoStart;
- /**
- * Holds the time at which the clock's `start()` method was last called.
- *
- * @type {number}
- * @default 0
- */
- this.startTime = 0;
- /**
- * Holds the time at which the clock's `start()`, `getElapsedTime()` or
- * `getDelta()` methods were last called.
- *
- * @type {number}
- * @default 0
- */
- this.oldTime = 0;
- /**
- * Keeps track of the total time that the clock has been running.
- *
- * @type {number}
- * @default 0
- */
- this.elapsedTime = 0;
- /**
- * Whether the clock is running or not.
- *
- * @type {boolean}
- * @default true
- */
- this.running = false;
- }
- /**
- * Starts the clock. When `autoStart` is set to `true`, the method is automatically
- * called by the class.
- */
- start() {
- this.startTime = now();
- this.oldTime = this.startTime;
- this.elapsedTime = 0;
- this.running = true;
- }
- /**
- * Stops the clock.
- */
- stop() {
- this.getElapsedTime();
- this.running = false;
- this.autoStart = false;
- }
- /**
- * Returns the elapsed time in seconds.
- *
- * @return {number} The elapsed time.
- */
- getElapsedTime() {
- this.getDelta();
- return this.elapsedTime;
- }
- /**
- * Returns the delta time in seconds.
- *
- * @return {number} The delta time.
- */
- getDelta() {
- let diff = 0;
- if ( this.autoStart && ! this.running ) {
- this.start();
- return 0;
- }
- if ( this.running ) {
- const newTime = now();
- diff = ( newTime - this.oldTime ) / 1000;
- this.oldTime = newTime;
- this.elapsedTime += diff;
- }
- return diff;
- }
- }
- function now() {
- return performance.now();
- }
- export { Clock };
|