haveno-ts/dist/utils/TaskLooper.js

69 lines
2.3 KiB
JavaScript
Raw Normal View History

2022-05-12 17:25:46 -04:00
"use strict";
/*
* Copyright Haveno
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2022-05-12 17:25:46 -04:00
Object.defineProperty(exports, "__esModule", { value: true });
2022-05-04 21:30:48 -04:00
/**
* Run a task in a fixed period loop.
*/
2022-05-12 17:25:46 -04:00
class TaskLooper {
2022-05-04 21:30:48 -04:00
/**
* Build the looper with a function to invoke on a fixed period loop.
*
* @param {function} fn - the async function to invoke
*/
constructor(fn) {
this._fn = fn;
this._isStarted = false;
this._isLooping = false;
}
/**
* Start the task loop.
*
2024-04-29 08:36:22 -04:00
* @param {number} periodInMs the loop period in milliseconds
* @param {boolean} targetFixedPeriod specifies if the task should target a fixed period by accounting for run time (default false)
* @return {TaskLooper} this instance for chaining
2022-05-04 21:30:48 -04:00
*/
2024-04-29 08:36:22 -04:00
start(periodInMs, targetFixedPeriod) {
if (periodInMs <= 0)
throw new Error("Looper period must be greater than 0 ms");
2022-05-04 21:30:48 -04:00
if (this._isStarted)
return;
this._isStarted = true;
2024-04-29 08:36:22 -04:00
this._runLoop(periodInMs, targetFixedPeriod);
2022-05-04 21:30:48 -04:00
}
/**
* Stop the task loop.
*/
stop() {
if (!this._isStarted)
throw new Error("Cannot stop TaskLooper because it's not started");
this._isStarted = false;
clearTimeout(this._timeout);
this._timeout = undefined;
}
2024-04-29 08:36:22 -04:00
async _runLoop(periodInMs, targetFixedPeriod) {
2022-05-04 21:30:48 -04:00
this._isLooping = true;
while (this._isStarted) {
const startTime = Date.now();
await this._fn();
if (this._isStarted)
2024-04-29 08:36:22 -04:00
await new Promise((resolve) => { this._timeout = setTimeout(resolve, periodInMs - (targetFixedPeriod ? (Date.now() - startTime) : 0)); });
2022-05-04 21:30:48 -04:00
}
this._isLooping = false;
}
}
2022-05-12 17:25:46 -04:00
exports.default = TaskLooper;
2022-05-04 21:30:48 -04:00
//# sourceMappingURL=TaskLooper.js.map