Skip to content

Commit

Permalink
Create waitFor function
Browse files Browse the repository at this point in the history
  • Loading branch information
leroykorterink committed May 29, 2024
1 parent aba651b commit 5eccab8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
30 changes: 30 additions & 0 deletions src/utils/waitFor/waitFor.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new WaitForTimeoutError());
}, timeout);

const intervalId = setInterval(() => {
if (callback()) {
clearTimeout(timeoutId);
clearInterval(intervalId);
resolve();
}
}, interval);
});
}

0 comments on commit 5eccab8

Please sign in to comment.