1 | const Mode = Object.freeze( { "interval":1, "timeout":2, "scheduled":3 } ); |
||
0 ignored issues
–
show
Backwards Compatibility
introduced
by
![]() |
|||
2 | // TODO: Properly handle promise based functions |
||
3 | class Periodic |
||
0 ignored issues
–
show
|
|||
4 | { |
||
5 | constructor( interval_ms, mode, func ) |
||
6 | { |
||
7 | // Private members |
||
8 | this._interval = interval_ms; |
||
9 | this._mode = Mode[ mode ]; |
||
10 | this._isRunning = false; |
||
11 | this._func = func; |
||
12 | this._reference = null; |
||
13 | } |
||
14 | |||
15 | // Private methods |
||
16 | _runTimeout() |
||
17 | { |
||
18 | var self = this; |
||
19 | |||
20 | if( self._isRunning ) |
||
21 | { |
||
22 | self._func(); |
||
23 | self._reference = setTimeout( self._runTimeout.bind( self ), self._interval ); |
||
24 | } |
||
25 | } |
||
26 | |||
27 | _runInterval() |
||
28 | { |
||
29 | var self = this; |
||
30 | |||
31 | if( self._isRunning ) |
||
32 | { |
||
33 | self._func(); |
||
34 | |||
35 | this._reference = setInterval( function() |
||
36 | { |
||
37 | if( self._isRunning ) |
||
38 | { |
||
39 | self._func(); |
||
40 | } |
||
41 | }, this._interval ); |
||
42 | } |
||
43 | } |
||
44 | |||
45 | // Public methods |
||
46 | start() |
||
47 | { |
||
48 | if( !this._isRunning ) |
||
49 | { |
||
50 | this._isRunning = true; |
||
51 | |||
52 | switch( this._mode ) |
||
53 | { |
||
54 | case Mode.timeout: |
||
55 | { |
||
56 | this._runTimeout(); |
||
57 | break; |
||
58 | } |
||
59 | |||
60 | case Mode.interval: |
||
61 | { |
||
62 | this._runInterval(); |
||
63 | break; |
||
64 | } |
||
65 | |||
66 | default: |
||
67 | { |
||
68 | throw new Error( "Mode not implemented!" ); |
||
69 | } |
||
70 | } |
||
71 | } |
||
72 | } |
||
73 | |||
74 | stop() |
||
75 | { |
||
76 | if( this._isRunning == true ) |
||
0 ignored issues
–
show
It is recommended to use
=== to compare with true .
Generally, it is recommended to use strict comparison whenever possible and not to rely on the weaker type-juggling comparison operator. ![]() |
|||
77 | { |
||
78 | this._isRunning = false; |
||
79 | |||
80 | if( this._reference ) |
||
81 | { |
||
82 | switch( this._mode ) |
||
83 | { |
||
84 | case Mode.timeout: |
||
85 | { |
||
86 | clearTimeout( this._reference ); |
||
87 | break; |
||
88 | } |
||
89 | |||
90 | case Mode.interval: |
||
91 | { |
||
92 | clearInterval( this._reference ); |
||
93 | break; |
||
94 | } |
||
95 | |||
96 | default: |
||
97 | { |
||
98 | throw new Errpr( "Mode not implemented!" ); |
||
99 | } |
||
100 | } |
||
101 | } |
||
102 | } |
||
103 | } |
||
104 | } |
||
105 | |||
106 | module.exports = Periodic; |