1
+ export class Timer
2
+ {
3
+ constructor ( ) {
4
+ this . timeouts = { }
5
+ this . intervals = { }
6
+ this . animations = { }
7
+ }
8
+
9
+ registerTimeout ( handler , timeout = null , ...args ) {
10
+ const id = window . setTimeout ( handler , timeout , ...args )
11
+ this . timeouts [ id ] = true
12
+ return id
13
+ }
14
+
15
+ offTimeout ( id = 0 ) {
16
+ if ( id ) {
17
+ if ( id in this . timeouts ) {
18
+ window . clearTimeout ( id )
19
+ delete this . timeouts [ id ]
20
+ }
21
+ return this
22
+ }
23
+ return this . offAllTimeouts ( )
24
+ }
25
+
26
+ offAllTimeouts ( ) {
27
+ Object . keys ( this . timeouts ) . forEach ( id => {
28
+ window . clearTimeout ( Number ( id ) )
29
+ delete this . timeouts [ id ]
30
+ } )
31
+ return this
32
+ }
33
+
34
+ registerInterval ( handler , timeout = null , ...args ) {
35
+ const id = window . setInterval ( handler , timeout , ...args )
36
+ this . intervals [ id ] = true
37
+ return id
38
+ }
39
+
40
+ offInterval ( id = 0 ) {
41
+ if ( id ) {
42
+ if ( id in this . intervals ) {
43
+ window . clearInterval ( id )
44
+ delete this . intervals [ id ]
45
+ }
46
+ return this
47
+ }
48
+ return this . offAllIntervals ( )
49
+ }
50
+
51
+ offAllIntervals ( ) {
52
+ Object . keys ( this . intervals ) . forEach ( id => {
53
+ window . clearInterval ( Number ( id ) )
54
+ delete this . intervals [ id ]
55
+ } )
56
+ return this
57
+ }
58
+
59
+ registerAnimation ( handler ) {
60
+ const id = window . requestAnimationFrame ( handler )
61
+ this . animations [ id ] = true
62
+ return id
63
+ }
64
+
65
+ offAnimation ( id = 0 ) {
66
+ if ( id ) {
67
+ if ( id in this . animations ) {
68
+ window . cancelAnimationFrame ( id )
69
+ delete this . animations [ id ]
70
+ }
71
+ return this
72
+ }
73
+ return this . offAllTimeouts ( )
74
+ }
75
+
76
+ offAllAnimations ( ) {
77
+ Object . keys ( this . animations ) . forEach ( id => {
78
+ window . cancelAnimationFrame ( Number ( id ) )
79
+ delete this . animations [ id ]
80
+ } )
81
+ return this
82
+ }
83
+
84
+ offAll ( ) {
85
+ return this . offAllTimeouts ( )
86
+ . offAllIntervals ( )
87
+ . offAllAnimations ( )
88
+ }
89
+ }
0 commit comments