From 4a196c2164284bb5fcfd8015fa1ff9f5b7df94ad Mon Sep 17 00:00:00 2001 From: Razzmatazz Date: Wed, 5 Jan 2022 15:47:26 -0600 Subject: [PATCH] add AbortSignal support to sleep module --- lib/sleep.function.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/sleep.function.ts b/lib/sleep.function.ts index 74f9407f..72caa380 100644 --- a/lib/sleep.function.ts +++ b/lib/sleep.function.ts @@ -1,5 +1,14 @@ -export const sleep = async (ms: number) => { - return new Promise(resolve => setTimeout(resolve, ms)); +import {setTimeout as setTimeoutPromise} from "timers/promises"; + +export const sleep = async (ms: number, signal?: AbortSignal) => { + const options = {signal: {aborted: false}}; + if (signal) options.signal = signal; + return setTimeoutPromise(ms, true, options).catch(err => { + if (err.name ==='AbortError') { + return Promise.resolve(true); + } + return Promise.reject(err); + }); }; export const busyWaitForNanoSeconds = (duration: number) => {