How can we specify the time upto which an element should remain on viewport in Intersection Observer

Viewed 66

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 Answers
    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);
            }
        };
    }, []);
Related