JavaScript triggered in the visible part of the browser

Hello everybody! A non-standard question today, but suddenly someone will come in handy: how to make JavaScript work in the visible part of the browser? Those. until we scroll down to the layer where this code hangs, it won’t run. The solution was suggested by my old friend, a JavaScript guru – for which thanks to him 🙂 I myself only dare to look at this JavaScript in more detail 🙂
So – here is the code of the page where our script is located:

182920661614619309a92f_000000

the red layer was made specially – for demonstration 🙂

And here is the script code itself, which should start as soon as it appears in the visible part of the browser:

var options = {
root: null,
rootMargin: '0px',
threshold: 1.0
}
var callback = function(entries, observer) { 
entries.map(item => {
if(item.isIntersecting) {
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
 
})
};
var observer = new IntersectionObserver(callback, options);
observer.observe(document.querySelector('.count'));

More fully it looks like this:

Thanks for attention 🙂