Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { EventEmitter } from "events";
- /** Timer class representing a Timer task. */
- export class Timer {
- /** The active state of the Timer. Has to be false to apply changes to the interval and callback function. */
- private _activeState: boolean;
- /** Gets the active state of the Timer. Has to be false to apply changes to the interval and callback function. */
- public get activeState(): boolean {
- return this._activeState;
- }
- /** The intervalId of the Timer. The inner object of the Timer provided by the native setInterval function. */
- private _intervalId: NodeJS.Timer;
- /** Gets the intervalId of the Timer. The inner object of the Timer provided by the native setInterval function. */
- public get intervalId(): NodeJS.Timer {
- return this._intervalId;
- }
- /** The interval in which the Timer should fire the callback function given in ms. */
- private _interval: number;
- /** The interval in which the Timer should fire the callback function given in ms. Can only be set if activeState is false. */
- public get interval(): number {
- return this._interval;
- }
- public set interval(value: number) {
- if (this._activeState === false) {
- this._interval = value;
- }
- }
- /** The callback event which the Timer should fire each interval. */
- private _callbackEvent: EventEmitter = new EventEmitter();
- /** The callback event which the Timer should fire each interval. */
- public get callbackEvent(): EventEmitter {
- return this._callbackEvent;
- }
- /**
- * Create a Timer.
- * @param interval - The interval in which the Timer should fire the callback function given in ms.
- */
- constructor(interval: number) {
- this._interval = interval;
- this._activeState = false;
- }
- /** Starts the Timer if the current activeState is false. */
- public start(): void {
- if (this._activeState === false) {
- this._intervalId = setInterval(() => {
- this.onTick();
- }, this._interval);
- this._activeState = true;
- }
- }
- /** Stops the Timer if the current activeState is true. */
- public stop(): void {
- if (this._activeState) {
- clearInterval(this._intervalId);
- this._intervalId = null;
- this._activeState = false;
- }
- }
- /** Fires the Timer tick manually and emits callback event. */
- public manuallyFireTick(): void {
- this.onTick();
- }
- /** Timer tick, emits the callback event. */
- private onTick(): void {
- this._callbackEvent.emit(null);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement