UNPKG

use-on-demand

Version:
65 lines 2.24 kB
/** * 经过调整的,精确的【Interval定时器】 * * 参考资料: * https://stackoverflow.com/a/44337628/6264260 * */ var AdjustingInterval = /** @class */ (function () { function AdjustingInterval(interval, workFunc, errorFunc) { this.interval = interval; this.workFunc = workFunc; this.errorFunc = errorFunc; this.expected = 0; this.timeout = 0; } /** * 带绑定上下文 */ AdjustingInterval.prototype._get_step_bind_fn = function () { // return this.step; return this.step.bind(this); // WARN 此处,必须绑定【this上下文】;不然之后的方法内获取不到this.xxx }; AdjustingInterval.prototype.start = function () { this.expected = Date.now() + this.interval; this.timeout = window.setTimeout(this._get_step_bind_fn(), // 带绑定上下文 this.interval); }; ; AdjustingInterval.prototype.stop = function () { window.clearTimeout(this.timeout); }; ; AdjustingInterval.prototype.step = function () { var drift = Date.now() - this.expected; // 漏掉了时间 if (drift > this.interval) { // console.log('漏掉了时间'); // You could have some default stuff here too... if (this.errorFunc) this.errorFunc(); } else { // console.log('正常运行'); } // 执行程序 this.workFunc(); this.expected += this.interval; this.timeout = window.setTimeout(this._get_step_bind_fn(), // 带绑定上下文 Math.max(0, this.interval - drift)); }; return AdjustingInterval; }()); var xX_STimer_Helper = /** @class */ (function () { function xX_STimer_Helper() { } xX_STimer_Helper.accurateInterval = function (interval, workFunc, errorFunc) { var adjustingInterval = new AdjustingInterval(interval, workFunc, errorFunc); adjustingInterval.start(); return adjustingInterval; }; ; return xX_STimer_Helper; }()); export { xX_STimer_Helper }; //# sourceMappingURL=STimer_Helper.js.map