Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Properly Destroy an Intersection Observer?

I am currently wrapping the IntersectionObserver API into a Svelte action. Part of this requires cleanup in a destroy() function, below is what I have.

function observe(node: HTMLElement, key: string) {
    const observer = new IntersectionObserver(nodes => {
        locations[key] = nodes[0]!.isIntersecting;
        locations = locations;
    });
    
    observer.observe(node);

    return {
        // this is the focus of my question
        destroy() {
            observer.unobserve(node);
        }
    }
}

Is there anything else I need to do to destroy the IntersectionObserver?

like image 210
kalkronline Avatar asked Oct 25 '25 08:10

kalkronline


1 Answers

According to the observe() docs:

To stop observing the element, call IntersectionObserver.unobserve().

So I think there's nothing more to be done.

Another alternative is to use observer.disconnect() to stop watching all of its target elements.

like image 55
Camilo Avatar answered Oct 26 '25 23:10

Camilo