Clock.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /**
  2. * Class for keeping track of time.
  3. */
  4. class Clock {
  5. /**
  6. * Constructs a new clock.
  7. *
  8. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  9. * `getDelta()` is called for the first time.
  10. */
  11. constructor( autoStart = true ) {
  12. /**
  13. * If set to `true`, the clock starts automatically when `getDelta()` is called
  14. * for the first time.
  15. *
  16. * @type {boolean}
  17. * @default true
  18. */
  19. this.autoStart = autoStart;
  20. /**
  21. * Holds the time at which the clock's `start()` method was last called.
  22. *
  23. * @type {number}
  24. * @default 0
  25. */
  26. this.startTime = 0;
  27. /**
  28. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  29. * `getDelta()` methods were last called.
  30. *
  31. * @type {number}
  32. * @default 0
  33. */
  34. this.oldTime = 0;
  35. /**
  36. * Keeps track of the total time that the clock has been running.
  37. *
  38. * @type {number}
  39. * @default 0
  40. */
  41. this.elapsedTime = 0;
  42. /**
  43. * Whether the clock is running or not.
  44. *
  45. * @type {boolean}
  46. * @default true
  47. */
  48. this.running = false;
  49. }
  50. /**
  51. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  52. * called by the class.
  53. */
  54. start() {
  55. this.startTime = now();
  56. this.oldTime = this.startTime;
  57. this.elapsedTime = 0;
  58. this.running = true;
  59. }
  60. /**
  61. * Stops the clock.
  62. */
  63. stop() {
  64. this.getElapsedTime();
  65. this.running = false;
  66. this.autoStart = false;
  67. }
  68. /**
  69. * Returns the elapsed time in seconds.
  70. *
  71. * @return {number} The elapsed time.
  72. */
  73. getElapsedTime() {
  74. this.getDelta();
  75. return this.elapsedTime;
  76. }
  77. /**
  78. * Returns the delta time in seconds.
  79. *
  80. * @return {number} The delta time.
  81. */
  82. getDelta() {
  83. let diff = 0;
  84. if ( this.autoStart && ! this.running ) {
  85. this.start();
  86. return 0;
  87. }
  88. if ( this.running ) {
  89. const newTime = now();
  90. diff = ( newTime - this.oldTime ) / 1000;
  91. this.oldTime = newTime;
  92. this.elapsedTime += diff;
  93. }
  94. return diff;
  95. }
  96. }
  97. function now() {
  98. return performance.now();
  99. }
  100. export { Clock };