Home > front end >  Start countdown with 3 second interval when reached to specific section in react
Start countdown with 3 second interval when reached to specific section in react

Time:12-09

  useEffect(() => {
console.log(window.scrollTo)
console.log(textInput.current.offsetTop);

}, [textInput,])

enter link description here

see bottom of this website same as countdown I want to make is there anyone with idea

CodePudding user response:

To start a countdown with a 3-second interval when reached a specific section in React, you can use the setInterval() method in combination with the scroll event.

First, you will need to add an event listener to the scroll event on the component that contains the section you want to trigger the countdown. Then, you can use the setInterval() method to create a countdown that updates every 3 seconds.

Here is an example of how you might implement this:

import React, { useState, useEffect } from "react";

function CountdownSection() {
  const [countdown, setCountdown] = useState(10);

  useEffect(() => {
    const section = document.getElementById("countdown-section");
    const interval = setInterval(() => {
      setCountdown(countdown - 1);
    }, 3000);

    function handleScroll(event) {
      if (section.getBoundingClientRect().top < window.innerHeight) {
        // Start the countdown when the section is in view
        setCountdown(10);
      }
    }

    window.addEventListener("scroll", handleScroll);

    return () => {
      clearInterval(interval);
      window.removeEventListener("scroll", handleScroll);
    };
  }, [countdown]);

  return (
    <div id="countdown-section">
      <p>Countdown: {countdown}</p>
    </div>
  );
}

export default CountdownSection;

In this example, the countdown starts at 10 and is decremented by 1 every 3 seconds using the setInterval() method. When the user scrolls and the "countdown-section" element is in view, the countdown is reset to 10. This continues until the countdown reaches 0, at which point the interval is cleared and the event listener is removed.

CodePudding user response:

You can use Intersection observer and few hooks to make this work. For example, I have a hook named useInView() that uses IntersectionObserver object and returns true if some element is in view or false if not. More about IntersectionObserver

useInView() hook:


    import React, { useState, useEffect } from 'react';
       
    const useInView = (element, rootMargin) => {
        const [isVisible, setIsVisible] = useState(false);
    
        useEffect(() => {
            const observer = new IntersectionObserver(
                ([entry]) => {
                    setIsVisible(entry.isIntersecting);
                },
                { rootMargin },
            );
            if (element.current) {
                observer.observe(element.current);
            }
    
            return () => observer.unobserve(element.current!);
        }, []);
        return isVisible;
    };
    
    export default useInView;

How to make this work:

  • First you need a useRef() hook to attach it to acomponent that you want to trigger the timer when user scrolls down to it.
  • Pass ref object to useInView() hook as an argument so you can utilize IntersectionObserver.
  • Create state with useState() so you can change state when timer is done
  • Create useEffect() and add value from isInView() as a dependecy so you can trigger side effect when component is in view.
  • In effect hook, set a timeout so after 3 seconds you can set your state to true
  • Render your component when your condition is satisfied

    const componentRef = useRef(null);
    const isInView = useInView(componentRef, '0px');
    const [timerDone, setTimerDone] = useState(false);
    
    useEffect(() => {
       setTimeout(() => {
          setTimerDone(true);
       }, 3000);
    }, [isInView]);

    <div ref={componentRef}>
       { timerDone && <Component /> }
    </div>


CodePudding user response:

// hooks
  const { ref: targetRef, inView: isVisible } = useInView();

const [countdown, setCountdown] = useState(3);

 useEffect(() => {

    let interval: any;
    // clearInterval(interval)

    if (isVisible && countdown === 0) {
      // @ts-ignore
      router.push(`/case-study/${parseInt(id) === 12 ? 1 : parseInt(id)   1}`)
      setCountdown(3)
    }  
    
    if (isVisible) {
      interval = setInterval(() => {
        setCountdown(countdown - 1);
      }, 1000);
    } else {
      setCountdown(3)

    }

    return () => {
      clearInterval(interval);
    };

  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isVisible, countdown])

https://www.npmjs.com/package/react-intersection-observer

https://spacejelly.dev/posts/how-to-trigger-a-function-when-scrolling-to-an-element-in-react-intersection-observer/

example and packages here.. try it

  • Related