Fixing bugs and adding default delay.

This commit is contained in:
Martin Karkowski 2021-09-17 09:53:38 +02:00
parent e426ce516e
commit 5c08c3be2b

View File

@ -28,11 +28,11 @@ export function isAsyncFunction(func: (...args) => any): boolean {
* @param {{ testFirst?: boolean; maxRetries?: number, timeout?: number, maxTimeout?: number }} [options={}] Options to enhance the
* @returns
*/
export function waitFor(testCallback: () => boolean | Promise<boolean>, options: { initialWait?: number, testFirst?: boolean; maxRetries?: number, timeout?: number, maxTimeout?: number, additionalDelay?: number } = {}): Promise<void> {
export function waitFor(testCallback: () => boolean | Promise<boolean>, options: { initialWait?: number, testFirst?: boolean; maxRetries?: number, delay?: number, maxTimeout?: number, additionalDelay?: number } = {}): Promise<void> {
const _options = Object.assign({
testFirst: true,
timeout: 50
delay: 50
}, options);
const _isAsync = isAsyncFunction(testCallback);
@ -79,6 +79,14 @@ export function waitFor(testCallback: () => boolean | Promise<boolean>, options:
interval = setInterval(async () => {
try {
if (_options.maxRetries && retryCounter > _options.maxRetries) {
// Clear out the Interval
clearInterval(interval);
// If there is a Timeout clear it as well;
if (timeout) {
clearTimeout(timeout);
}
reject(new RangeError("Max Retries has been reached"));
} else if (await testCallback()) {
@ -96,7 +104,7 @@ export function waitFor(testCallback: () => boolean | Promise<boolean>, options:
} catch (err) {
reject(err);
}
});
}, _options.delay);
}
} catch (e) {
reject(e);
@ -144,6 +152,14 @@ export function waitFor(testCallback: () => boolean | Promise<boolean>, options:
interval = setInterval(() => {
try {
if (_options.maxRetries && retryCounter > _options.maxRetries) {
// Clear out the Interval
clearInterval(interval);
// If there is a Timeout clear it as well;
if (timeout) {
clearTimeout(timeout);
}
reject(new RangeError("Max Retries has been reached"));
} else if (testCallback()) {
@ -161,7 +177,7 @@ export function waitFor(testCallback: () => boolean | Promise<boolean>, options:
} catch (err) {
reject(err);
}
});
}, _options.delay);
}
} catch (e) {
reject(e);