Last active
July 23, 2022 16:45
-
-
Save kevinweber/49452321ed3b88f53d3214110db03fac to your computer and use it in GitHub Desktop.
Poll function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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