UNPKG

@mezzy/commands

Version:

A luxurious user experience framework, developed by your friends at Mezzanine.

71 lines 3.08 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const is_1 = require("@mezzy/is"); const result_1 = require("@mezzy/result"); const command_1 = require("./command"); class ThrottlingCommand extends command_1.default { constructor(runFunction, undoFunction, scope, delayInMilliseconds = 250) { super(runFunction, undoFunction, scope); this._last = 0; this.delayInMilliseconds = delayInMilliseconds; } debounce(...args) { if (is_1.default.empty(this.runFunction)) return result_1.Result.resolve(null); if (is_1.default.notEmpty(args) && args.length > 0) this.runArgs = args; if (is_1.default.notEmpty(this._timeout)) clearTimeout(this._timeout); let returnValue; let resultReturnValue = new result_1.Result(); if (this.delayInMilliseconds <= 0) { returnValue = this.runFunction.apply(this.scope, this.runArgs); if (returnValue instanceof result_1.Result) returnValue.then((value) => resultReturnValue.resolve(value)); else resultReturnValue.resolve(returnValue); } else this._timeout = setTimeout(() => { returnValue = this.runFunction.apply(this.scope, this.runArgs); if (returnValue instanceof result_1.Result) returnValue.then((value) => resultReturnValue.resolve(value)); else resultReturnValue.resolve(returnValue); }, this.delayInMilliseconds); return resultReturnValue; } throttle(...args) { if (is_1.default.empty(this.runFunction)) return result_1.Result.resolve(null); if (is_1.default.notEmpty(args) && args.length > 0) this.runArgs = args; let returnValue; let resultReturnValue = new result_1.Result(); let now = +new Date; if (this._last > 0 && now < this._last + this.delayInMilliseconds) { if (is_1.default.notEmpty(this._timeout)) clearTimeout(this._timeout); this._timeout = setTimeout(() => { this._last = now; returnValue = this.runFunction.apply(this.scope, this.runArgs); if (returnValue instanceof result_1.Result) returnValue.then((value) => resultReturnValue.resolve(value)); else resultReturnValue.resolve(returnValue); }, this.delayInMilliseconds); } else { this._last = now; returnValue = this.runFunction.apply(this.scope, this.runArgs); if (returnValue instanceof result_1.Result) returnValue.then((value) => resultReturnValue.resolve(value)); else resultReturnValue.resolve(returnValue); } return resultReturnValue; } } exports.ThrottlingCommand = ThrottlingCommand; exports.default = ThrottlingCommand; //# sourceMappingURL=throttlingCommand.js.map