Timer.class.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. * @returns {Date} - the amount of time the timer has been paused
  55. */
  56. getTimePaused() {
  57. if (!this.paused) {
  58. return this.timeWhenPaused;
  59. }
  60. return Date.now() - this.timePaused;
  61. }
  62. }