Skip to content

Commit

Permalink
TaskLooper does not target fixed period by default
Browse files Browse the repository at this point in the history
  • Loading branch information
woodser committed Apr 30, 2024
1 parent 4ea5025 commit 6b289cc
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/utils/TaskLooper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,15 @@ export default class TaskLooper {
/**
* Start the task loop.
*
* @param {int} periodInMs the loop period in milliseconds
* @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
*/
start(periodInMs: number) {
start(periodInMs: number, targetFixedPeriod: boolean) {
if (periodInMs <= 0) throw new Error("Looper period must be greater than 0 ms");
if (this._isStarted) return;
this._isStarted = true;
this._runLoop(periodInMs);
this._runLoop(periodInMs, targetFixedPeriod);
}

/**
Expand All @@ -58,12 +60,12 @@ export default class TaskLooper {
this._timeout = undefined;
}

async _runLoop(periodInMs: number) {
async _runLoop(periodInMs: number, targetFixedPeriod: boolean) {
this._isLooping = true;
while (this._isStarted) {
const startTime = Date.now();
await this._fn();
if (this._isStarted) await new Promise((resolve) => { this._timeout = setTimeout(resolve, periodInMs - (Date.now() - startTime)); });
if (this._isStarted) await new Promise((resolve) => { this._timeout = setTimeout(resolve, periodInMs - (targetFixedPeriod ? (Date.now() - startTime) : 0)); });
}
this._isLooping = false;
}
Expand Down

0 comments on commit 6b289cc

Please sign in to comment.