javascript – automatic content change react.js

  // This function both initializes, and then at any time resets, the
  // interval that causes the periodic setting of cards
  const resetInterval = ()=>{
    if(intervalRef.current){
      clearInterval(intervalRef.current);
    }
    intervalRef.current = setInterval(() => {
      const nextIndex = (activeIndex + 1) % expertise.length;
      setActiveIndex(nextIndex);
      ;
    }, 7000);
  }

  // whenever the currently active index changes, 
  // we clear the exististing interval and set a new one
  useEffect(() => {
    resetInterval()
  
    return () => clearInterval(intervalRef.current);
  }, [activeIndex]);
  
  // whenever the user interacts we clear the existing interval and
  // set a new one.
  const handleCardClick = (index) => {
    setActiveIndex(index);
    resetInterval()
  };

Whenever a user clicks a card, you can clear the interval and start it again. That way it will always be a full 7 seconds between every card change. I think that was your problem?

The other interpretation i can see of your question is that you are having trouble synchronizing the active index variable. I don’t think that you should have an issue with the code above, I think it should stay synced, but if you are having trouble you could start using a ref to track the current index:

If you do this, the interval handler will always know what the active index is.

  const currentIndexRef = React.useRef(activeIndex)
  currentIndexRef.current = activeIndex;


  const resetInterval = ()=>{
    if(intervalRef.current){
      clearInterval(intervalRef.current);
    }
    intervalRef.current = setInterval(() => {
      const nextIndex = (currentIndexRef.current + 1) % expertise.length;
      setActiveIndex(nextIndex);
      ;
    }, 7000);
  }

  useEffect(() => {
    resetInterval()
  
    return () => clearInterval(intervalRef.current);
  }, [activeIndex]);
  
  const handleCardClick = (index) => {
    setActiveIndex(index);
    resetInterval()
  };

Read more here: Source link