Created
June 3, 2015 16:23
-
-
Save jfairbank/9bb7da0e60eeac5b55fa to your computer and use it in GitHub Desktop.
poll promise
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
function poll(fn, timeout, interval) { | |
var endTime = Number(new Date()) + (timeout || 2000); | |
interval = interval || 100; | |
return new Promise(function(resolve, reject) { | |
(function p() { | |
// If the condition is met, we're done! | |
if (fn()) { | |
resolve(); | |
} | |
// If the condition isn't met but the timeout hasn't elapsed, go again | |
else if (Number(new Date()) < endTime) { | |
setTimeout(p, interval); | |
} | |
// Didn't match and too much time, reject! | |
else { | |
reject('timed out for ' + fn + ': ' + arguments); | |
} | |
})(); | |
}); | |
} | |
poll(function() { | |
return document.getElementById('lightbox').offsetWidth > 0; | |
}).then(function() { | |
// Done | |
}).catch(function() { | |
// Fail | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment