@jingoz/await-timer
Version:
@jingoz/await-timer 是一个 npm 包,提供了实现轮询功能的能力,用于替代 setInterval,并且可以确保传入的回调函数执行完毕后再开始下一次的循环。
2 lines (1 loc) • 1.23 kB
JavaScript
(function(i,t){typeof exports=="object"&&typeof module<"u"?t(exports):typeof define=="function"&&define.amd?define(["exports"],t):(i=typeof globalThis<"u"?globalThis:i||self,t(i.awaitTimer={}))})(this,function(i){"use strict";var n=Object.defineProperty;var h=(i,t,e)=>t in i?n(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var s=(i,t,e)=>h(i,typeof t!="symbol"?t+"":t,e);class t{constructor(o,a,r){s(this,"_timer",null);s(this,"_isStopped",!0);s(this,"_options",{immediate:!1,autoStart:!0});this._callback=o,this._delay=a,r&&(this._options={...this._options,...r}),this._options.autoStart&&this.start()}get isStopped(){return this._isStopped}async _invokeCallback(){try{await this._callback()}catch(o){throw console.error("An Error Occured while polling"),o}}_runLoop(){this._isStopped||(this._timer&&clearTimeout(this._timer),this._timer=setTimeout(async()=>{await this._invokeCallback(),this._runLoop()},this._delay))}async start(){this._isStopped=!1,this._options.immediate&&await this._invokeCallback(),this._runLoop()}stop(){this._timer&&clearTimeout(this._timer),this._isStopped=!0}destroy(){this.stop(),this._timer=null}}i.AwaitTimer=t,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})});