Timer.class.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. module.exports = class Timer {
  2. constructor(callback, delay, paused) {
  3. this.callback = callback;
  4. this.timerId = undefined;
  5. this.start = undefined;
  6. this.paused = paused;
  7. this.remaining = delay;
  8. this.timeWhenPaused = 0;
  9. this.timePaused = Date.now();
  10. if (!paused) {
  11. this.resume();
  12. }
  13. }
  14. pause() {
  15. clearTimeout(this.timerId);
  16. this.remaining -= Date.now() - this.start;
  17. this.timePaused = Date.now();
  18. this.paused = true;
  19. }
  20. ifNotPaused() {
  21. if (!this.paused) {
  22. this.resume();
  23. }
  24. }
  25. resume() {
  26. this.start = Date.now();
  27. clearTimeout(this.timerId);
  28. this.timerId = setTimeout(this.callback, this.remaining);
  29. this.timeWhenPaused = Date.now() - this.timePaused;
  30. this.paused = false;
  31. }
  32. resetTimeWhenPaused() {
  33. this.timeWhenPaused = 0;
  34. }
  35. getTimePaused() {
  36. if (!this.paused) {
  37. return this.timeWhenPaused;
  38. } else {
  39. return Date.now() - this.timePaused;
  40. }
  41. }
  42. };