Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Last active July 23, 2022 16:45
Show Gist options
  • Save kevinweber/49452321ed3b88f53d3214110db03fac to your computer and use it in GitHub Desktop.
Save kevinweber/49452321ed3b88f53d3214110db03fac to your computer and use it in GitHub Desktop.
Poll function
/**
* Poll function
* based on https://davidwalsh.name/essential-javascript-functions
*/
function poll(fn, callback, errback, timeout, interval) {
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
(function p() {
// If the condition is met, we're done!
if (fn()) {
callback();
} else if (Number(new Date()) < endTime) {
setTimeout(p, interval);
} else {
errback(new Error('timed out for ' + fn + ': ' + arguments));
}
}());
}
// Use it like this ...
poll(
function () {
// Condition
return that.value.length;
},
// Success
function () {
// ...
},
// Error
function () {
// ...
},
3000, // Poll timeout
50 // Poll interval
);
export default function poll(
fn,
timeout,
intervalArg,
timeoutMessage,
) {
const endTime = Number(new Date()) + (timeout || 2000);
const interval = intervalArg || 100;
const checkCondition = (resolve, reject) => {
// If the condition is met, we're done!
const result = fn();
if (result) {
resolve(result);
// If the condition isn't met but the timeout hasn't elapsed, go again
} else if (Number(new Date()) < endTime) {
setTimeout(checkCondition, interval, resolve, reject);
// Didn't match and too much time, reject!
} else {
reject(new Error(timeoutMessage));
}
};
return new Promise(checkCondition);
}
///// Use like this:
poll(
() => !window.ethereum.selectedAddress, // Condition
10000, // Timeout
100, // Poll interval
'No ETH address available', // Timeout error
).then(callback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment