Skip to content

Instantly share code, notes, and snippets.

@jancimajek
Created May 7, 2023 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jancimajek/99c206c4dfdacddaf9296b1dfd5b11c9 to your computer and use it in GitHub Desktop.
Save jancimajek/99c206c4dfdacddaf9296b1dfd5b11c9 to your computer and use it in GitHub Desktop.
TS Samples
console.clear();
const appStart = Date.now();
const delay = async (delayMs: number) => new Promise(res => setTimeout(res, delayMs));
const waitFor = async (checkFn: () => Promise<boolean>, maxWaitMs = 5000, pollIntervalMs = 250): Promise<void> => {
const start = Date.now();
// const waitForIt = async (start: number): Promise<void> => {
// const check = await checkFn();
// const elapsedMs = Date.now() - start;
// console.log('waitForIt', {
// check,
// start,
// elapsedMs,
// maxWaitMs,
// timeout: elapsedMs > maxWaitMs,
// pollIntervalMs,
// })
// if (check === true) return;
// if (elapsedMs > maxWaitMs) throw new Error('Max wait time reached');
// await delay(pollIntervalMs);
// return await waitForIt(start);
// }
const waitForCheck = async (): Promise<void> => {
if (await checkFn() === true) return;
if (Date.now() - start > maxWaitMs) throw new Error('Max wait time reached');
await delay(pollIntervalMs);
return await waitForCheck();
}
return await waitForCheck();
}
let x = 3;
const testCheck = async () => {
console.log('Waiting for a second', x);
await new Promise(res => setTimeout(res, 2500));
console.log('Done waiting', x);
return --x === 0;
}
(async () => {
try {
await waitFor(testCheck);
console.log('YYYYYYYYYYYYYYYYYYYY Check passed');
} catch(err) {
console.log('XXXXXXXXXXXXXXXXXXXX Check timed out');
};
console.log({ Finished: Date.now() - appStart });
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment