* Executes the given function with a specified timeout. * If the function takes longer than the timeout, it will be interrupted and an error will be thrown. * The total execution time of the function will be stored in the totalTime property. * * @returns The result of the executed functi
()
| 28 | * @throws An error with a message indicating the function was interrupted due to exceeding the specified timeout. |
| 29 | */ |
| 30 | public async exec() { |
| 31 | const signal = AbortSignal.timeout(this.timeout); |
| 32 | this.timeoutPromise = new Promise<never>((_, reject) => { |
| 33 | signal!.addEventListener( |
| 34 | 'abort', |
| 35 | () => { |
| 36 | this.onAbort?.(); |
| 37 | reject(this.errorFn()); |
| 38 | }, |
| 39 | { once: true }, |
| 40 | ); |
| 41 | }); |
| 42 | |
| 43 | const start = Date.now(); |
| 44 | const result = await Promise.race<T>([this.fn(signal), this.timeoutPromise]); |
| 45 | this.totalTime = Date.now() - start; |
| 46 | return result; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Returns the interrupt promise associated with the TimeoutTask instance. |
no test coverage detected