This repository has been archived by the owner on Jun 16, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
poller.js
79 lines (73 loc) · 2.57 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
/**
* Variant of $interval() which only starts the interval
* when at least one user is interested.
*/
define('factories/poller', [
'factories/ng-factories',
], function (module) {
"use strict";
return module.factory('Poller', [
'$interval',
function($interval) {
/**
* Ref-counted $interval.
* Starts calling `callback` every `interval` milliseconds when
* number of calls to `start()` is bigger than number of calls to `stop()`.
*
* Usage example:
* const p = new Poller(10000, () => { console.log("tick"); });
* // when instantiating controller:
* p.start();
* // when destroying controller:
* p.stop();
*/
function Poller(interval, callback) {
this._interval = interval;
this._callback = callback;
this._refs = 0;
this._handle = undefined; // $interval handle
}
/**
* Enable polling.
* Multiple calls to start() can be made. As long as the number of
* stop() calls is smaller than the number of start() calls, the
* poller keeps running.
*/
Poller.prototype.start = function () {
this._refs++;
this.reset();
};
/**
* Disable polling when the number of stop calls is equal to
* the number of start calls.
* It is an error to call stop more often than start.
*/
Poller.prototype.stop = function () {
if (this._refs <= 0) {
throw new Error("start/stop calls mismatched");
}
this._refs--;
if (this._refs === 0) {
// Keep timer running if others are still interested
this.reset();
}
};
/**
* Restart poller, if it is currently running.
*/
Poller.prototype.reset = function() {
var self = this;
if (this._handle !== undefined) {
$interval.cancel(this._handle);
this._handle = undefined;
}
if (this._refs > 0) {
this._handle = $interval(function () {
self._callback();
}, this._interval);
}
};
return Poller;
}
]);
});