Source: lib/util/timer.js

  1. /**
  2. * @license
  3. * Copyright 2016 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. goog.provide('shaka.util.Timer');
  18. /**
  19. * A simple cancelable timer.
  20. * @param {Function} callback
  21. * @constructor
  22. * @struct
  23. */
  24. shaka.util.Timer = function(callback) {
  25. /** @private {?number} */
  26. this.id_ = null;
  27. /** @private {Function} */
  28. this.callback_ = (function() {
  29. this.id_ = null;
  30. callback();
  31. }.bind(this));
  32. };
  33. /**
  34. * Cancel the timer, if it's running.
  35. */
  36. shaka.util.Timer.prototype.cancel = function() {
  37. if (this.id_ != null) {
  38. clearTimeout(this.id_);
  39. this.id_ = null;
  40. }
  41. };
  42. /**
  43. * Schedule the timer, canceling any previous scheduling.
  44. * @param {number} seconds
  45. */
  46. shaka.util.Timer.prototype.schedule = function(seconds) {
  47. this.cancel();
  48. this.id_ = setTimeout(this.callback_, seconds * 1000);
  49. };
  50. /**
  51. * Schedule the timer, canceling any previous scheduling. The timer will
  52. * automatically reschedule after the callback fires.
  53. * @param {number} seconds
  54. */
  55. shaka.util.Timer.prototype.scheduleRepeated = function(seconds) {
  56. this.cancel();
  57. let repeat = (function() {
  58. this.callback_();
  59. this.id_ = setTimeout(repeat, seconds * 1000);
  60. }.bind(this));
  61. this.id_ = setTimeout(repeat, seconds * 1000);
  62. };