Skip to content

Commit 706a12e

Browse files
Add TimerPromise Promise to wrap engine.xTimer() API
1 parent 4c31c4c commit 706a12e

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

res/controllers/common-controller-scripts.js

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,77 @@ var colorCodeToObject = function(colorCode) {
140140
var script = function() {
141141
};
142142

143+
/**
144+
* Wraps the engine timer API in JS promises
145+
*
146+
* Use `new TimerPromise()` to call `engine.beginTimer`, use {@link TimerPromise#cancel} to call `engine.stopTimer()`.
147+
* The Promise resolves the first time the timer completes and rejects when canceled.
148+
*/
149+
class TimerPromise extends Promise {
150+
/**
151+
* @param {number} interval Time in milliseconds until the function is executed. Intervals below 20ms are ignored
152+
* @param {boolean} oneShot If true the function is only once, if false the function is executed repeatedly and the
153+
* promise resolves the first time the timer completes. [default = false]
154+
*/
155+
constructor(interval, oneShot = false) {
156+
let resolve = undefined;
157+
let reject = undefined;
158+
super((res, rej) => {
159+
resolve = res;
160+
reject = rej;
161+
});
162+
163+
this._resolve = resolve;
164+
this._reject = reject;
165+
166+
this.__timer = 0;
167+
if (Number.isInteger(interval) && interval >= 20) {
168+
this.__timer = engine.beginTimer(interval, () => {
169+
this.__done = true;
170+
this.__canceled = false;
171+
this._resolve();
172+
}, oneShot);
173+
}
174+
175+
}
176+
177+
get settled() {
178+
return this.__done || this.__canceled;
179+
}
180+
181+
get done() {
182+
return this.__done;
183+
}
184+
185+
get canceled() {
186+
return this.__canceled;
187+
}
188+
189+
cancel() {
190+
if (this.__done || this.__canceled) { return; }
191+
this.__done = false;
192+
this.__canceled = true;
193+
if (this.__timer !== 0) {
194+
engine.stopTimer(this.__timer);
195+
}
196+
this._reject();
197+
}
198+
}
199+
200+
TimerPromise.resolve = function resolve(value) {
201+
const promise = new TimerPromise(0);
202+
promise._resolve(value);
203+
return promise;
204+
};
205+
206+
TimerPromise.cancelled = function cancelled() {
207+
const promise = new TimerPromise(0);
208+
promise.cancel();
209+
return promise;
210+
};
211+
212+
script.TimerPromise = TimerPromise;
213+
143214
/**
144215
* Discriminates whether an object was created using the `{}` synthax.
145216
*

0 commit comments

Comments
 (0)