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