{"version":3,"file":"editable-timeout.mjs","names":[],"sources":["../../src/utils/editable-timeout.ts"],"sourcesContent":["/**\n * A wrapper around <code>setTimeout()</code> and <code>clearTimeout()</code>\n * that allows the timer to be edited to complete earlier or later,\n * relative to its original start time.\n */\nexport class EditableTimeout {\n  public readonly callback: () => void;\n\n  public readonly startTime: number;\n  public runTime: number;\n\n  public runningTimeout: NodeJS.Timeout | undefined;\n  public completed = false;\n\n  public constructor(callback: () => void, runTime: number) {\n    this.callback = callback;\n    this.startTime = Date.now();\n\n    /**\n     * Time in milliseconds of when <code>callback</code> should be invoked,\n     * relative to {@link startTime}.\n     */\n    this.runTime = runTime;\n\n    this.updateTimer();\n  }\n\n  public stop(): boolean {\n    if (this.runningTimeout == null) {\n      // no stop was performed\n      return false;\n    } else {\n      clearTimeout(this.runningTimeout);\n      return true;\n    }\n  }\n\n  public update(newRunTime: number): void {\n    if (this.completed) {\n      return;\n    }\n\n    this.runTime = newRunTime;\n\n    this.updateTimer();\n  }\n\n  private updateTimer(): void {\n    this.stop();\n\n    // calculate time the new setTimeout needs to run\n    let timeRemaining;\n    if (this.runningTimeout == null) {\n      // this is the first invocation by the constructor\n      timeRemaining = this.runTime;\n    } else {\n      const currentTime = Date.now();\n      const alreadyPassed = currentTime - this.startTime;\n      timeRemaining = this.runTime - alreadyPassed;\n    }\n\n    this.runningTimeout = setTimeout(\n      this.invokeCallback.bind(this),\n      timeRemaining,\n    );\n  }\n\n  private invokeCallback(): void {\n    this.completed = true;\n    this.callback();\n  }\n}\n"],"mappings":";;;;;;AAKA,IAAa,kBAAb,MAA6B;CAC3B;CAEA;CACA;CAEA;CACA,YAAmB;CAEnB,YAAmB,UAAsB,SAAiB;AACxD,OAAK,WAAW;AAChB,OAAK,YAAY,KAAK,KAAK;;;;;AAM3B,OAAK,UAAU;AAEf,OAAK,aAAa;;CAGpB,OAAuB;AACrB,MAAI,KAAK,kBAAkB,KAEzB,QAAO;OACF;AACL,gBAAa,KAAK,eAAe;AACjC,UAAO;;;CAIX,OAAc,YAA0B;AACtC,MAAI,KAAK,UACP;AAGF,OAAK,UAAU;AAEf,OAAK,aAAa;;CAGpB,cAA4B;AAC1B,OAAK,MAAM;EAGX,IAAI;AACJ,MAAI,KAAK,kBAAkB,KAEzB,iBAAgB,KAAK;OAChB;GAEL,MAAM,gBADc,KAAK,KAAK,GACM,KAAK;AACzC,mBAAgB,KAAK,UAAU;;AAGjC,OAAK,iBAAiB,WACpB,KAAK,eAAe,KAAK,KAAK,EAC9B,cACD;;CAGH,iBAA+B;AAC7B,OAAK,YAAY;AACjB,OAAK,UAAU"}