Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
setInterval triggers a function exponentially

I have a function that changes the value of a string variable to one from a list at set intervals. I figured setInterval would be ideal for this task but It behaves very strangely.

When the program loads, after the first interval delay, it will trigger the function twice, then a couple more times on the next interval. It progressively ramps up until it's triggering the function hundreds of times per interval.

From what I can understand, it's nothing to do with the function itself since I set up a manual trigger for the function and it works normally. (Whenever I call the function manually, it triggers once.)

const [dynString, setDynString] = useState(List[Index]);
setInterval(textTick, 5000);

function textTick(){
        Index = Index + 1;
        if(Index >= List.length){
            Index = 0;
        }
        setDynString(List[Index]);
        console.log('Current String:', Index);
    }

return(
    <div className='text-tick-object'>
        <h1 onClick={textTick}>{dynString}</h1>
    </div>
);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should create intervals (side effects in general) inside useEffect() hooks. Any time the component re-renders (when you change the state inside the interval or after a click event) a new interval will start. You only need the interval once, at start

I would suggest something like this:

const list = ["a", "b", "c", "d"];

function MyComponent() {
  const [index, setIndex] = useState(0);

  const textTick = useCallback(() => {
    setIndex((index) => {
      let nextIndex = index + 1;
      if (nextIndex >= list.length) {
        nextIndex = 0;
      }
      console.log("Current String:", nextIndex);
      return nextIndex;
    });
  }, []);

  useEffect(() => {
    const interval = setInterval(textTick, 5000);

    return () => {
      clearInterval(interval);
    };
  }, [textTick]);

  return (
    <div className="text-tick-object">
      <h1 onClick={textTick}>{list[index]}</h1>
    </div>
  );
}

You can see this running in: https://stackblitz.com/edit/react-vn9hxx?file=src/App.js

(it's an external link, might not work in the future, the code is the same)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!