This repository has been archived by the owner on Nov 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
looper.js
166 lines (148 loc) · 4.58 KB
/
looper.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/**
* An exception used to shut down the loop.
*
* User code should not need to be aware of this class.
*/
class InterruptLooper extends Error {
constructor(message) {
super(message);
this.name = "InterruptLooper";
}
}
/**
* An exception thrown when calling stop() multiple times.
*/
class LooperAlreadyStopping extends Error {
constructor(message) {
super(message);
this.name = "LooperAlreadyStopping";
}
}
/**
* An exception thrown when calling start() multiple times.
*/
class LooperAlreadyRunning extends Error {
constructor(message) {
super(message);
this.name = "LooperAlreadyRunning";
}
}
function sleep(ms=0)
{
return new Promise(function(resolve) { setTimeout(resolve, ms); });
}
/**
* Run a loop in the background.
*
* - async function updateFunc runs every updateTime ms
* - Error in updateFunc calls errorCallback but does not stop the loop
* - Call start() to start the loop
* - Call stop() to stop the loop
* - Does not guarantee updateFunc() will not be called after stop
*/
class Looper {
constructor( updateFunc, updateTime, errorCallback ) {
this.updateFunc = updateFunc;
this.updateTime = updateTime;
this.errorCallback = errorCallback;
this._joinWaiters = [];
this._runningUpdateLoop = null;
this._interruptResolve = null;
}
/**
* Return a promise that resolves when this task is finished.
*/
join() {
let resolve = null;
let prom = new Promise(function(res) { resolve = res; });
if( this._runningUpdateLoop === null ) {
// Not running, so join() will return a promise that resolves immediately
resolve();
}
else {
// Running, so join() will add to _joinWaiters
this._joinWaiters.push(resolve);
}
return prom;
}
/**
* Ask the loop to stop. Return a promise that resolves when the loop has stopped.
*
* If stop() was already called, immediately throw a LooperAlreadyStopping exception.
*/
stop() {
if( this._interruptResolve == null ) {
throw new LooperAlreadyStopping();
}
// Call _interruptResolve() to fire the promise.
setTimeout( this._interruptResolve, 0 );
this._interruptResolve = null;
return this.join();
}
try_stop() {
if( this._interruptResolve !== null ) {
setTimeout( this._interruptResolve, 0 );
this._interruptResolve = null;
}
return this.join();
}
/**
* Start the loop. Fire-and-forget.
*
* If start() was already called, immediately throw a LooperAlreadyStarting exception.
*/
start() {
if( this._runningUpdateLoop !== null ) {
throw new LooperAlreadyRunning();
}
// Create promise for interrupt.
let reject = null;
let prom = new Promise( function(res, rej) { reject = rej; } );
// _interruptResolve() will inject an InterruptLooper exception into the loop.
this._interruptResolve = function() { reject( new InterruptLooper("Interrupt") ); };
this._runningUpdateLoop = this._updateLoop(prom); // Fire-and-forget
}
/**
* The main loop.
*
* Runs forever, until _interruptPromise is triggered.
* You should call start() instead of calling this method directly.
*/
async _updateLoop( _interruptPromise ) {
while( true )
{
try
{
await Promise.race( [ _interruptPromise, sleep( (0.75 + 0.5*Math.random()) * this.updateTime ) ] );
await Promise.race( [ _interruptPromise, this.updateFunc()] );
}
catch( e )
{
if( e.name === "InterruptLooper" )
break;
if (this.errorCallback && typeof this.errorCallback === "function") {
this.errorCallback(e);
}
}
}
//
// Use setTimeout(f, 0) here so we don't immediately call external code which might attempt to mutate
// this._joinWaiters during the loop.
//
// If join() is called before we get to this point, the result will be resolved due to the following loop.
// If join() is called after this point, it will correctly return a resolved promise due to _runningUpdateLoop == null.
//
for( let i=0; i<this._joinWaiters.length; i++ ) {
setTimeout( this._joinWaiters[i], 0 );
}
this._runningUpdateLoop = null;
this._joinWaiters = [];
}
}
module.exports = {
Looper : Looper,
InterruptLooper : InterruptLooper,
LooperAlreadyStopping : LooperAlreadyStopping,
LooperAlreadyRunning : LooperAlreadyRunning,
sleep : sleep
};