// In Deno (Goldsky) timers are the web API returning a number, which has no unref export type TimerId = NodeJS.Timeout | number; type TimeoutCallback = ( resolve: (value: T | PromiseLike) => void, reject: (reason?: unknown) => void ) => void; export const timeoutOrResult = async ( prom: Promise, timeoutMS?: number, customErrorMessage?: string, timeoutCallback?: TimeoutCallback ): Promise => { return await (timeoutMS ? timeout(prom, timeoutMS, customErrorMessage, timeoutCallback) : prom); }; export const timeout = async ( prom: Promise, timeoutMS: number, customErrorMessage?: string, timeoutCallback?: TimeoutCallback ): Promise => { let timer: NodeJS.Timeout | undefined; try { return await Promise.race([ prom, new Promise( (resolve, reject) => (timer = setTimeout(() => { if (timeoutCallback) { return timeoutCallback(resolve, reject); } reject(new Error(customErrorMessage ?? `Timeout error ${timeoutMS} [MS]`)); }, timeoutMS)) ), ]); } finally { clearTimeout(timer); } }; export const timeoutWithCustomError = async ( prom: Promise, timeoutMS: number, customError: Error ): Promise => { let timer: NodeJS.Timeout | undefined; try { return await Promise.race([ prom, new Promise( (_resolve, reject) => (timer = setTimeout(() => { reject(customError); }, timeoutMS)) ), ]); } finally { clearTimeout(timer); } }; export const setUnrefInterval = (callback: () => void, intervalMs: number) => { const timer: TimerId = setInterval(callback, intervalMs); if (typeof timer !== "number") { timer.unref(); } return timer; }; export const sleep = (ms: number) => new Promise((resolve, _rejects) => setTimeout(resolve, ms)); export const msToMin = (ms: number) => ms / 60_000; export const hourToMin = (fullHour: number, minRemainder: number = 0) => fullHour * 60 + minRemainder; export const secToMs = (sec: number) => sec * 1_000; export const minToMs = (min: number) => min * 60_000; export const hourToMs = (hours: number) => hours * 3_600_000; export const daysToMs = (days: number) => days * 86_400_000; export const msToHours = (ms: number) => ms / 3_600_000; export const msToDays = (ms: number) => ms / (3_600_000 * 24); export const nsToMs = (ns: number) => ns / 1_000_000; export const hourToSecs = (hours: number) => hours * 3_600; export const secsToHours = (secs: number) => secs / 3_600; export const secsToMs = (secs: number) => secs * 1_000; export const msToSecs = (ms: number) => ms / 1_000; export const microsecsToSecs = (microsecs: number): number => microsecs / 1_000_000; export const microsecsToMs = (microsecs: number): number => microsecs / 1_000; export const daysToYearFraction = (days: number): number => days / 365; export const intervalMsToCronFormat = (intervalMs: number) => { // edge case for every minute if (intervalMs === 60_000) { return `0 * * * * *`; } return `*/${intervalMs / 1000} * * * * *`; };