Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create waitFor function #344

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
}
Loading