Recipe 6.2
Wrapping an IntersectionObserver with a Promise
You can promisify an IntersectionObserver by wrapping it in a Promise constructor, and resolving
the Promise once the isIntersecting property becomes true.
Code
JavaScript
/**
* Returns a Promise that is resolved once the given element becomes visible.
*/
function waitForElement(element) {
return new Promise(resolve => {
const observer = new IntersectionObserver(entries => {
if (entries[0].isIntersecting) {
observer.disconnect();
resolve();
}
});
observer.observe(element);
});
}