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); + }); +}