Skip to content
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);
});
}