@openhps/core
Version:
Open Hybrid Positioning System - Core component
61 lines • 1.63 kB
JavaScript
import { Node } from '../../Node';
import { TimeUnit } from '../../utils';
/**
* @category Flow shape
*/
export class FrameChunkNode extends Node {
constructor(count, timeout, timeoutUnit = TimeUnit.MILLISECOND, options) {
super(options);
this._queue = [];
this._count = count;
if (timeout) {
this._interval = timeoutUnit.convert(timeout, TimeUnit.MILLISECOND);
this.once('build', this._start.bind(this));
this.once('destroy', this._stop.bind(this));
}
this.on('push', this._onPush.bind(this));
}
_onPush(frame) {
return new Promise((resolve, reject) => {
this._queue.push(frame);
if (this._queue.length >= this._count) {
this._flushQueue().then(resolve).catch(reject);
} else {
resolve();
}
});
}
_flushQueue() {
return new Promise(resolve => {
// Restart the timeout
if (this._timer !== undefined) {
clearInterval(this._timer);
this._timer = setInterval(this._timeoutFn.bind(this), this._interval);
}
this.outlets.forEach(outlet => outlet.push(this._queue));
this._queue = [];
resolve();
});
}
_timeoutFn() {
if (this._queue.length > 0) {
Promise.resolve(this._flushQueue());
}
}
/**
* Start the timeout timer
* @returns {Promise<void>} Start promise
*/
_start() {
return new Promise(resolve => {
this._timer = setInterval(this._timeoutFn.bind(this), this._interval);
resolve();
});
}
_stop() {
if (this._timer !== undefined) {
clearInterval(this._timer);
this._timer = undefined;
}
}
}