Timer.class.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. export default class Timer {
  2. // eslint-disable-next-line require-jsdoc
  3. constructor(callback, delay, paused) {
  4. this.callback = callback;
  5. this.timerId = undefined;
  6. this.start = undefined;
  7. this.paused = paused;
  8. this.remaining = delay;
  9. this.timeWhenPaused = 0;
  10. this.timePaused = Date.now();
  11. if (!paused) {
  12. this.resume();
  13. }
  14. }
  15. /**
  16. * Pauses the timer
  17. *
  18. */
  19. pause() {
  20. clearTimeout(this.timerId);
  21. this.remaining -= Date.now() - this.start;
  22. this.timePaused = Date.now();
  23. this.paused = true;
  24. }
  25. /**
  26. * Ensures the timer's resume function is called if it is paused
  27. *
  28. */
  29. ifNotPaused() {
  30. if (!this.paused) {
  31. this.resume();
  32. }
  33. }
  34. /**
  35. * Resumes the timer
  36. *
  37. */
  38. resume() {
  39. this.start = Date.now();
  40. clearTimeout(this.timerId);
  41. this.timerId = setTimeout(this.callback, this.remaining);
  42. this.timeWhenPaused = Date.now() - this.timePaused;
  43. this.paused = false;
  44. }
  45. /**
  46. * Resets the time when paused
  47. *
  48. */
  49. resetTimeWhenPaused() {
  50. this.timeWhenPaused = 0;
  51. }
  52. /**
  53. * Gets the amount of time the timer has been paused
  54. *
  55. * @returns {Date} - the amount of time the timer has been paused
  56. */
  57. getTimePaused() {
  58. if (!this.paused) {
  59. return this.timeWhenPaused;
  60. }
  61. return Date.now() - this.timePaused;
  62. }
  63. }