'Why do IntersectionObservers created in a function continue to work after the function call finishes

Reading through the Mozilla Developer Network explanation of the IntersectionObserver, I encountered this section which is part of an example use case for the IntersectionObserver. The way that the article is creating the IntersectionObserver works well in the context of the code I have for a project I am working on, but I am a little confused about how the IntersectionObserver continues to work even though the observer variable used to store the IntersectionObserver instance is declared with function scope. Shouldn't the the IntersectionObserver be garbage collected along with the observer variable when the function call finishes?

In my own code, I have the following function expression that applies the same logic used in the MDN article. It's working perfectly as far as I can tell, but I am curious to know why it works.

const intersectionObserverFactory = function(rootMargin, targetList) {
    let observer;

    let options = {
        threshold: [1],
        rootMargin: rootMargin,
    };

    observer = new IntersectionObserver(entries => {
        for(let entry of entries){
            entry.target.classList.toggle("is-stuck", entry.intersectionRatio < 1)
        }
    }, options);

    targetList.forEach(header => {
        observer.observe(header);
    });
}

I am relatively new to JavaScript and completely new to web development. It's entirely possible that there is a simple explanation as to why this works, I just don't know the right terminology to use to find the answer to my question. It's also possible that this behavior is not unique to IntersectionObserver, it's just the context in which I've observed it.



Solution 1:[1]

You must explicitly stop observing

Even if you no longer have a reference to the observer that you can access from Javascript, the observer is still busy observing. If you want to stop it from doing so, do this:

observer.unobserve(header);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eureka