I'm trying out Intersection Observer API but I have come to a dead end when I use setInverval
with it.
So I have this div
which have width and height of 500px. If the div is in viewport I want to trigger setInterval
which will log something every 3 seconds. But if I scroll and the div is outside the viewport I want to clear that interval. That is, stop the interval and stop the logging altogether.
Right now when I scroll and the div is in viewport, the setInterval
and the logging starts but if I scroll again and the div is not in the viewport the setInterval
and the logging doesn't stop.
What am I doing wrong here?
Here's the snippet:
const mainContainer = document.querySelector('#main-container');
const callback = (entries, observer) => {
entries.forEach(item => {
let intervalVar;
if (item.isIntersecting) {
intervalVar = setInterval(() => {
console.log('div is in viewport');
}, 3000);
} else {
console.log('div is not in viewport');
clearInterval(intervalVar);
}
})
};
const options = {
threshold: 0.1
};
const observer = new IntersectionObserver(callback, options);
observer.observe(mainContainer);
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="main-container" style="width: 540px; height: 440px;"></div>