Skip to content

Instantly share code, notes, and snippets.

@neofreko
Created June 1, 2018 01:16
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 neofreko/a22a6c5096e49aa7864b22bdcb0b5334 to your computer and use it in GitHub Desktop.
Save neofreko/a22a6c5096e49aa7864b22bdcb0b5334 to your computer and use it in GitHub Desktop.
wait until condition becomes truthy. Inspired by former works or wait-until libraries and tutorials.
const waitUntil = async (asyncCondition, timeoutMs) => {
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const intervalMs = 1000;
const startTime = Date.now();
const result = await asyncCondition();
const endTime = Date.now();
const timeSpentMs = endTime - startTime;
console.log(`checking waitUntil condition, timeout in: ${timeoutMs}ms`);
if (result) return result;
if (timeoutMs - timeSpentMs - intervalMs < 0) return result;
await wait(intervalMs);
return await waitUntil(asyncCondition, timeoutMs - timeSpentMs - intervalMs);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment