UNPKG

@dotmh/tick

Version:

A utility library for making polling loops

51 lines (50 loc) 1.31 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Tick = void 0; const ms_1 = __importDefault(require("ms")); class Tick { constructor() { this._tick = false; this._time = 1000; this._condition = () => true; } get time() { return (0, ms_1.default)(this._time); } get mTime() { return this._time; } get lTime() { return (0, ms_1.default)(this._time, { long: true }); } every(timeString) { this._time = Number((0, ms_1.default)(timeString)); return this; } when(condition) { this._condition = condition; return this; } start(callback) { this._tick = true; this.tick(callback); } stop() { if (this._timeOutId) { clearTimeout(this._timeOutId); } this._tick = false; } tick(callback) { if (this._tick) { if (this._condition !== null && this._condition()) { callback(); this._timeOutId = setTimeout(() => this.tick(callback), this._time); } } } } exports.Tick = Tick;