-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpoller.js
98 lines (78 loc) · 2.15 KB
/
poller.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import debugFactory from 'debug';
const debug = debugFactory( 'calypso:poller' );
const DEFAULT_INTERVAL = 30000;
let _id = 0;
function Poller( dataStore, fetcher, options ) {
options = options || {};
this.id = _id;
_id++;
this.paused = false;
this.startOnFirstChange = this.startOnFirstChange.bind( this );
this.stopOnNoChangeListeners = this.stopOnNoChangeListeners.bind( this );
this.interval = options.interval || DEFAULT_INTERVAL;
this.pauseWhenHidden = true;
if ( 'pauseWhenHidden' in options ) {
this.pauseWhenHidden = options.pauseWhenHidden;
}
if ( options.leading !== undefined ) {
this.leading = !! options.leading;
} else {
this.leading = true;
}
this.dataStore = dataStore;
this.fetcher = fetcher;
this.dataStore.on( 'newListener', this.startOnFirstChange );
this.dataStore.on( 'removeListener', this.stopOnNoChangeListeners );
if ( this.dataStore.listeners( 'change' ).length > 0 ) {
this.start();
}
}
Poller.prototype.start = function () {
const fetch = () => {
debug( 'Calling fetcher for %o', { fetcher: this.fetcher, store: this.dataStore } );
this.fetch();
};
if ( ! this.timer ) {
debug( 'Starting poller for %o', this.dataStore );
if ( this.leading ) {
fetch();
}
this.timer = setInterval( fetch, this.interval );
this.paused = false;
}
};
Poller.prototype.stop = function () {
if ( this.timer ) {
debug( 'Stopping poller for %o', this.dataStore );
clearInterval( this.timer );
this.timer = false;
this.paused = false;
}
};
Poller.prototype.fetch = function () {
if ( typeof this.fetcher === 'string' ) {
this.dataStore[ this.fetcher ]();
} else {
this.fetcher.call( null );
}
};
Poller.prototype.clear = function () {
this.dataStore.off( 'newListener', this.startOnFirstChange );
this.dataStore.off( 'removeListener', this.stopOnNoChangeListeners );
this.stop();
};
Poller.prototype.startOnFirstChange = function ( event ) {
if ( event !== 'change' ) {
return;
}
this.start();
};
Poller.prototype.stopOnNoChangeListeners = function ( event ) {
if ( event !== 'change' ) {
return;
}
if ( this.dataStore.listeners( 'change' ).length === 0 ) {
this.stop();
}
};
export default Poller;