Source: lib/util/timer.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.Timer');
  7. goog.require('shaka.util.DelayedTick');
  8. /**
  9. * A timer allows a single function to be executed at a later time or at
  10. * regular intervals.
  11. *
  12. * @final
  13. * @export
  14. */
  15. shaka.util.Timer = class {
  16. /**
  17. * Create a new timer. A timer is committed to a single callback function.
  18. * While there is no technical reason to do this, it is far easier to
  19. * understand and use timers when they are connected to one functional idea.
  20. *
  21. * @param {function()} onTick
  22. */
  23. constructor(onTick) {
  24. /**
  25. * Each time our timer "does work", we call that a "tick". The name comes
  26. * from old analog clocks.
  27. *
  28. * @private {function()}
  29. */
  30. this.onTick_ = onTick;
  31. /** @private {shaka.util.DelayedTick} */
  32. this.ticker_ = null;
  33. }
  34. /**
  35. * Have the timer call |onTick| now.
  36. *
  37. * @return {!shaka.util.Timer}
  38. * @export
  39. */
  40. tickNow() {
  41. this.stop();
  42. this.onTick_();
  43. return this;
  44. }
  45. /**
  46. * Have the timer call |onTick| after |seconds| has elapsed unless |stop| is
  47. * called first.
  48. *
  49. * @param {number} seconds
  50. * @return {!shaka.util.Timer}
  51. * @export
  52. */
  53. tickAfter(seconds) {
  54. this.stop();
  55. this.ticker_ = new shaka.util.DelayedTick(() => {
  56. this.onTick_();
  57. }).tickAfter(seconds);
  58. return this;
  59. }
  60. /**
  61. * Have the timer call |onTick| every |seconds| until |stop| is called.
  62. *
  63. * @param {number} seconds
  64. * @return {!shaka.util.Timer}
  65. * @export
  66. */
  67. tickEvery(seconds) {
  68. this.stop();
  69. if (goog.DEBUG) {
  70. // Capture the stack trace by making a fake error.
  71. const stackTrace = Error('Timer created').stack;
  72. shaka.util.Timer.activeTimers.set(this, stackTrace);
  73. }
  74. this.ticker_ = new shaka.util.DelayedTick(() => {
  75. // Schedule the timer again first. |onTick_| could cancel the timer and
  76. // rescheduling first simplifies the implementation.
  77. this.ticker_.tickAfter(seconds);
  78. this.onTick_();
  79. }).tickAfter(seconds);
  80. return this;
  81. }
  82. /**
  83. * Stop the timer and clear the previous behaviour. The timer is still usable
  84. * after calling |stop|.
  85. *
  86. * @export
  87. */
  88. stop() {
  89. if (this.ticker_) {
  90. this.ticker_.stop();
  91. this.ticker_ = null;
  92. }
  93. if (goog.DEBUG) {
  94. shaka.util.Timer.activeTimers.delete(this);
  95. }
  96. }
  97. };
  98. if (goog.DEBUG) {
  99. /**
  100. * Tracks all active timer instances, along with the stack trace that created
  101. * that timer.
  102. * @type {!Map<!shaka.util.Timer, string>}
  103. */
  104. shaka.util.Timer.activeTimers = new Map();
  105. }