@@ -2,18 +2,21 @@ import { PollOptions } from './types'
2
2
3
3
export class Poll {
4
4
protected id : number | null = null
5
- protected inBackground = false
5
+ protected throttle = false
6
6
protected keepAlive = false
7
- protected currentInterval : number
8
- protected originalInterval : number
7
+ protected cb : VoidFunction
8
+ protected interval : number
9
+ protected cbCount = 0
9
10
10
11
constructor ( interval : number , cb : VoidFunction , options : PollOptions ) {
11
12
this . keepAlive = options . keepAlive || false
12
13
13
- this . currentInterval = interval
14
- this . originalInterval = interval
14
+ this . cb = cb
15
+ this . interval = interval
15
16
16
- this . start ( interval , cb )
17
+ if ( options . autoStart || true ) {
18
+ this . start ( )
19
+ }
17
20
}
18
21
19
22
public stop ( ) {
@@ -22,28 +25,25 @@ export class Poll {
22
25
}
23
26
}
24
27
25
- public isInBackground ( hidden : boolean ) {
26
- this . inBackground = this . keepAlive ? false : hidden
27
-
28
- if ( this . inBackground ) {
29
- // Throttle requests by 95% when the page is in the background
30
- this . currentInterval = Math . round ( this . originalInterval / 0.05 )
31
- } else {
32
- // Otherwise, restore the original interval
33
- this . currentInterval = this . originalInterval
34
- }
35
- }
28
+ public start ( ) {
29
+ this . stop ( )
36
30
37
- protected start ( interval : number , cb : VoidFunction ) {
38
31
this . id = window . setInterval ( ( ) => {
39
- if ( this . currentInterval === interval ) {
40
- cb ( )
41
- return
32
+ if ( ! this . throttle || this . cbCount % 10 === 0 ) {
33
+ this . cb ( )
34
+ }
35
+
36
+ if ( this . throttle ) {
37
+ this . cbCount ++
42
38
}
39
+ } , this . interval )
40
+ }
43
41
44
- // The visibility has changed, so we need to adjust the interval
45
- this . stop ( )
46
- this . start ( this . currentInterval , cb )
47
- } , interval )
42
+ public isInBackground ( hidden : boolean ) {
43
+ this . throttle = this . keepAlive ? false : hidden
44
+
45
+ if ( this . throttle ) {
46
+ this . cbCount = 0
47
+ }
48
48
}
49
49
}
0 commit comments