Skip to content

Instantly share code, notes, and snippets.

@dejanvasic85
Created January 2, 2020 23:40
Show Gist options
  • Select an option

  • Save dejanvasic85/5c54172face7454ae9e34414ee92a12f to your computer and use it in GitHub Desktop.

Select an option

Save dejanvasic85/5c54172face7454ae9e34414ee92a12f to your computer and use it in GitHub Desktop.
Polling in javascript
const poll = async (fn: any, timeout: number, interval: number) => {
const endTime = Date.now() + timeout;
const checkCondition = async (resolve: any, reject: any) => {
const result = await fn();
if (result) {
resolve(result);
} else if (Date.now() < endTime) {
setTimeout(checkCondition, interval, resolve, reject);
} else {
reject(new Error(`Timed out during polling.`));
}
};
return new Promise(checkCondition);
};
@dejanvasic85
Copy link
Author

Usage:

await poll(
        async () => { 
              return someCondition;
   }, 30000, 1000
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment