Advertisement
Guest User

Untitled

a guest
Dec 10th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. import { EventEmitter } from "events";
  2.  
  3. /** Timer class representing a Timer task. */
  4. export class Timer {
  5. /** The active state of the Timer. Has to be false to apply changes to the interval and callback function. */
  6. private _activeState: boolean;
  7. /** Gets the active state of the Timer. Has to be false to apply changes to the interval and callback function. */
  8. public get activeState(): boolean {
  9. return this._activeState;
  10. }
  11.  
  12. /** The intervalId of the Timer. The inner object of the Timer provided by the native setInterval function. */
  13. private _intervalId: NodeJS.Timer;
  14. /** Gets the intervalId of the Timer. The inner object of the Timer provided by the native setInterval function. */
  15. public get intervalId(): NodeJS.Timer {
  16. return this._intervalId;
  17. }
  18.  
  19. /** The interval in which the Timer should fire the callback function given in ms. */
  20. private _interval: number;
  21. /** The interval in which the Timer should fire the callback function given in ms. Can only be set if activeState is false. */
  22. public get interval(): number {
  23. return this._interval;
  24. }
  25. public set interval(value: number) {
  26. if (this._activeState === false) {
  27. this._interval = value;
  28. }
  29. }
  30.  
  31. /** The callback event which the Timer should fire each interval. */
  32. private _callbackEvent: EventEmitter = new EventEmitter();
  33. /** The callback event which the Timer should fire each interval. */
  34. public get callbackEvent(): EventEmitter {
  35. return this._callbackEvent;
  36. }
  37.  
  38. /**
  39. * Create a Timer.
  40. * @param interval - The interval in which the Timer should fire the callback function given in ms.
  41. */
  42. constructor(interval: number) {
  43. this._interval = interval;
  44. this._activeState = false;
  45. }
  46.  
  47. /** Starts the Timer if the current activeState is false. */
  48. public start(): void {
  49. if (this._activeState === false) {
  50. this._intervalId = setInterval(() => {
  51. this.onTick();
  52. }, this._interval);
  53. this._activeState = true;
  54. }
  55. }
  56.  
  57. /** Stops the Timer if the current activeState is true. */
  58. public stop(): void {
  59. if (this._activeState) {
  60. clearInterval(this._intervalId);
  61. this._intervalId = null;
  62. this._activeState = false;
  63. }
  64. }
  65.  
  66. /** Fires the Timer tick manually and emits callback event. */
  67. public manuallyFireTick(): void {
  68. this.onTick();
  69. }
  70.  
  71. /** Timer tick, emits the callback event. */
  72. private onTick(): void {
  73. this._callbackEvent.emit(null);
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement