Created
January 27, 2018 07:10
-
-
Save amitmbee/7606ca25c93ff419c045c6fcbdbb59a0 to your computer and use it in GitHub Desktop.
Poll.js
This file contains hidden or 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 | |
//As I mentioned with the debounce function, sometimes you don't get to plug into an event to signify a desired state -- if //the event doesn't exist, you need to check for your desired state at intervals: | |
// The polling function | |
function poll(fn, timeout, interval) { | |
var endTime = Number(new Date()) + (timeout || 2000); | |
interval = interval || 100; | |
var checkCondition = function(resolve, reject) { | |
// If the condition is met, we're done! | |
var 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('timed out for ' + fn + ': ' + arguments)); | |
} | |
}; | |
return new Promise(checkCondition); | |
} | |
// Usage: ensure element is visible | |
poll(function() { | |
return document.getElementById('lightbox').offsetWidth > 0; | |
}, 2000, 150).then(function() { | |
// Polling done, now do something else! | |
}).catch(function() { | |
// Polling timed out, handle the error! | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment