Search code examples
javascriptintersection-observer

ClearTimeout through intersectionObserver


I have the following code which loads the next project in a portfolio based on an intersectionObserver result being true. However, if the user scrolls out and the intersectionObserver returns false, I want to stop the redirection. This is not happening, and the page simply reloads after 5 seconds.

handleIntersect(intersecting) {
    if (intersecting) {
      console.log("Is intersecting");
      this.element.classList.add("animate");
      this.timeout = setTimeout(() => {
        window.location.href = this.href;
      }, 5200);
    }

    if (!intersecting) {
      console.log("Is not intersecting");
      this.element.classList.remove("animate");

      if (this.timeout) {
        clearTimeout(this.timeout);
        this.timeout = null;
        console.log('clearing Timeout' + this.timeout);
      }
    }
  }

I do get all messages in console confirming the "clearing timeout null" message when I scroll out of the element. Maybe I am missing something in the window.locatoion.href.


Solution

  • Try clearing the timeout before you call setTimeout each time. I have a feeling you're creating multiple timeouts and overwriting the this.timeout variable.

    if (intersecting) {
      console.log("Is intersecting");
      this.element.classList.add("animate");
      if (this.timeout) {
        clearTimeout(this.timeout);
      }
      this.timeout = setTimeout(() => {
        window.location.href = this.href;
      }, 5200);
    }