Timer.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. class Timer {
  2. constructor() {
  3. this._previousTime = 0;
  4. this._currentTime = 0;
  5. this._startTime = now();
  6. this._delta = 0;
  7. this._elapsed = 0;
  8. this._timescale = 1;
  9. this._document = null;
  10. this._pageVisibilityHandler = null;
  11. }
  12. connect( document ) {
  13. this._document = document;
  14. // use Page Visibility API to avoid large time delta values
  15. if ( document.hidden !== undefined ) {
  16. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  17. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  18. }
  19. }
  20. disconnect() {
  21. if ( this._pageVisibilityHandler !== null ) {
  22. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  23. this._pageVisibilityHandler = null;
  24. }
  25. this._document = null;
  26. }
  27. getDelta() {
  28. return this._delta / 1000;
  29. }
  30. getElapsed() {
  31. return this._elapsed / 1000;
  32. }
  33. getTimescale() {
  34. return this._timescale;
  35. }
  36. setTimescale( timescale ) {
  37. this._timescale = timescale;
  38. return this;
  39. }
  40. reset() {
  41. this._currentTime = now() - this._startTime;
  42. return this;
  43. }
  44. dispose() {
  45. this.disconnect();
  46. return this;
  47. }
  48. update( timestamp ) {
  49. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  50. this._delta = 0;
  51. } else {
  52. this._previousTime = this._currentTime;
  53. this._currentTime = ( timestamp !== undefined ? timestamp : now() ) - this._startTime;
  54. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  55. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  56. }
  57. return this;
  58. }
  59. }
  60. class FixedTimer extends Timer {
  61. constructor( fps = 60 ) {
  62. super();
  63. this._delta = ( 1 / fps ) * 1000;
  64. }
  65. update() {
  66. this._elapsed += ( this._delta * this._timescale ); // _elapsed is the accumulation of all previous deltas
  67. return this;
  68. }
  69. }
  70. function now() {
  71. return performance.now();
  72. }
  73. function handleVisibilityChange() {
  74. if ( this._document.hidden === false ) this.reset();
  75. }
  76. export { Timer, FixedTimer };
粤ICP备19079148号