From 5eccab835a871fccdfa2e9b7b72534825a0d7964 Mon Sep 17 00:00:00 2001 From: Leroy Korterink Date: Wed, 29 May 2024 09:45:32 +0200 Subject: [PATCH] Create waitFor function --- src/index.ts | 1 + src/utils/waitFor/waitFor.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 src/utils/waitFor/waitFor.ts diff --git a/src/index.ts b/src/index.ts index 815250e..89365a6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -39,3 +39,4 @@ export * from './utils/arrayRef/arrayRef.js'; export * from './utils/createTimeout/createTimeout.js'; export * from './utils/isRefObject/isRefObject.js'; export * from './utils/unref/unref.js'; +export * from './utils/waitFor/waitFor.js'; diff --git a/src/utils/waitFor/waitFor.ts b/src/utils/waitFor/waitFor.ts new file mode 100644 index 0000000..a3fc410 --- /dev/null +++ b/src/utils/waitFor/waitFor.ts @@ -0,0 +1,30 @@ +export class WaitForTimeoutError extends Error { + public constructor() { + super('Timeout error while waiting for condition'); + this.name = 'WaitForTimeoutError'; + } +} + +export type WaitForOptions = { + interval?: number; + timeout?: number; +}; + +export function waitFor( + callback: () => boolean, + { interval = 10, timeout = 1000 }: WaitForOptions = {}, +): Promise { + return new Promise((resolve, reject) => { + const timeoutId = setTimeout(() => { + reject(new WaitForTimeoutError()); + }, timeout); + + const intervalId = setInterval(() => { + if (callback()) { + clearTimeout(timeoutId); + clearInterval(intervalId); + resolve(); + } + }, interval); + }); +}