Source: lib/util/delayed_tick.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.DelayedTick');
  7. /**
  8. * @summary
  9. * This class wraps a function so that we can defer executing the function by X
  10. * seconds.
  11. *
  12. * @final
  13. */
  14. shaka.util.DelayedTick = class {
  15. /**
  16. * @param {function()} onTick
  17. */
  18. constructor(onTick) {
  19. /** @private {function()} */
  20. this.onTick_ = onTick;
  21. /** @private {?function()} */
  22. this.cancelPending_ = null;
  23. }
  24. /**
  25. * Call |onTick| after |delayInSeconds| has elapsed. If there is already a
  26. * pending call to |onTick|, the pending call will be canceled.
  27. *
  28. * @param {number} delayInSeconds
  29. * @return {!shaka.util.DelayedTick}
  30. */
  31. tickAfter(delayInSeconds) {
  32. // We only want one timeout set at a time, so make sure no other timeouts
  33. // are running.
  34. this.stop();
  35. // We will wrap these values in a function to allow us to cancel the timeout
  36. // we are about to create.
  37. let alive = true;
  38. let timeoutId = null;
  39. this.cancelPending_ = () => {
  40. window.clearTimeout(timeoutId);
  41. alive = false;
  42. };
  43. // For some reason, a timeout may still execute after we have cleared it in
  44. // our tests. We will wrap the callback so that we can double-check our
  45. // |alive| flag.
  46. const onTick = () => {
  47. if (alive) {
  48. this.onTick_();
  49. }
  50. };
  51. timeoutId = window.setTimeout(onTick, delayInSeconds * 1000);
  52. return this;
  53. }
  54. /**
  55. * Cancel any pending calls to |onTick|. If there are no pending calls to
  56. * |onTick|, this will be a no-op.
  57. */
  58. stop() {
  59. if (this.cancelPending_) {
  60. this.cancelPending_();
  61. this.cancelPending_ = null;
  62. }
  63. }
  64. };