Home > Software design >  How to execute scroll function every 3 seconds with useEffect React
How to execute scroll function every 3 seconds with useEffect React

Time:07-15

I am trying to build a component that auto scrolls through some list, forwards and then backwards.

  const [clicks, setClicks] = useState(numOfClicks)
  const [goingUp, setGoingUp] = useState(true)

  const scroll = () => {
    if (goingUp) {
      elementsRef.current[current   1].current.scrollIntoView();
      setCurrent(current   1);
      setClicks(clicks - 1);
    } else {
      elementsRef.current[current - 1].current.scrollIntoView();
      setCurrent(current - 1);
      setClicks(clicks - 1);
    }
  }

if clicks reaches 0 the list is at its end and then it flips around and goes backwards until it reaches the start and then the cycle repeats.

  useEffect(() => {
    if (clicks === 0) {
      setGoingUp(!goingUp);
      setClicks(numOfClicks);
    }
  }, [clicks])

up to this point, it works fine via click events. My last phase is to execute scroll automatically within the component after an interval. For this I use an additional useEffect

useEffect(() => {
    const interval = setInterval(() => {
      scroll()
    }, TIMER);

    return () => clearInterval(interval); // This represents the unmount function, in which you need to clear your interval to prevent memory leaks.
  }, [])

The function runs once and then never again. Although if I add a console.log within the effect I see the interval is in fact working.

CodePudding user response:

clearInterval is causing the setInterval to stop after 3 sec , it only run once , put your clearInterval inside a condition which will specify when you want this to stop

useEffect(() => {
    const interval = setInterval(() => {
      scroll()
    }, TIMER);

 return () => clearInterval(interval); 

  }, [clicks])
  • Related