UNPKG

tsbase

Version:

Base class libraries for TypeScript

81 lines 2.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConditionalTimer = void 0; const Timer_1 = require("./Timer"); /** * A timer that performs an action over time based on the evaluation of a condition */ class ConditionalTimer { constructor(timer) { this.timer = timer || new Timer_1.Timer(100); } /** * Short hand for creating a new instance of ConditionalTimer * @param interval */ static Instance(interval) { return new ConditionalTimer(new Timer_1.Timer(interval)); } /** * Performs the given action one time after the condition evaluates to true * @param action * @param condition */ async DoWhen(action, condition) { this.resetTimer(); return await new Promise(async (resolve) => { this.timer.Elapsed.push(() => { if (condition()) { action(); this.resetTimer(); resolve(); } }); await this.timer.Start(); }); } /** * Performs the given action repeatedly until the condition evaluates to true * @param action * @param condition */ async DoUntil(action, condition) { return this.getRepeatingConditionalTimer(action, condition); } /** * Performs the given action repeatedly as long as the condition evaluates to true * @param action * @param condition */ async DoWhile(action, condition) { return this.getRepeatingConditionalTimer(action, () => !condition()); } /** * Stops the underlying timer, preventing further execution */ Stop() { this.timer.Stop(); } async getRepeatingConditionalTimer(action, condition) { this.resetTimer(); return await new Promise(async (resolve) => { this.timer.Elapsed.push(() => { action(); if (condition()) { this.resetTimer(); resolve(); } }); await this.timer.Start(); }); } resetTimer() { if (this.timer.Enabled) { this.Stop(); this.timer.AutoReset = true; this.timer.Elapsed = []; } } } exports.ConditionalTimer = ConditionalTimer; //# sourceMappingURL=ConditionalTimer.js.map