1

I am using Intersection Observer API in react to detect an element coming on viewport. But I also want that the element should remain on viewport for minimum 3 seconds and detected after that. How can I do so? Give below is the code I am using.

    const callBack = (entries) => {
    const [entry] = entries;
    if (entry.isIntersecting) {
      console.log("intersecting");
    }
  };

  const options = {
    root: null,
    rootMargin: "0px",
    threshold: 0.75,
  };

  useEffect(() => {
    const observer = new IntersectionObserver(callBack, options);
    if (cardRef.current) {
      observer.observe(cardRef.current);
    }
    return () => {
      if (cardRef.current) {
        observer.unobserve(cardRef.current);
      }
    };
  }, []);

1 Answers1

0
    const callBack = (entries) => {
        const [entry] = entries; //объект текущего пересечения элемента

        //если пересечение началось и элемент entry.target входит в root
        if (entry.isIntersecting) {
            //создаём таймер с ууказанием нужной задержки перед срабатыванием
            let id = setTimeout(() => {
                console.log("intersecting");
            }, 3000);

            entry.target.start_intersecting_timeout_id = id; //в свойства start_intersecting_timeout_id нашего entry.target элемента записываем id этого таймера
        }
        //если пересечение началось и элемент entry.target входит в root

        //если пересечение началось и элемент entry.target покидает root, или при первом старте не находится в root
        else {
            //если у нашего entry.target есть свойство start_intersecting_timeout_id
            if (entry.target.start_intersecting_timeout_id) {
                clearTimeout(entry.target.start_intersecting_timeout_id); //удаляем этот таймаут
                delete entry.target.start_intersecting_timeout_id; //удаляем свойство
            }
        }
        //если пересечение началось и элемент entry.target покидает root, или при первом старте не находится в root
    }

    const options = {
        root: null,
        rootMargin: "0px",
        threshold: 0.75,
    }

    useEffect(() => {
        const observer = new IntersectionObserver(callBack, options);
        if (cardRef.current) {
            observer.observe(cardRef.current);
        }
        return () => {
            if (cardRef.current) {
                observer.unobserve(cardRef.current);
            }
        };
    }, []);
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 28 '22 at 04:03