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

74
Views
setTimeout in useEffect hook

I am attempting to make it so that a different page from an array is displayed every 5 seconds. I currently have it working, except the page isn't always switching every 5 seconds, but sometimes 10 or 15 seconds. I believe this to be because I am not clearing the timeout correctly, any suggestions?

const pages = [
    'screen1', 'screen2'
];

const [displayedPage, setDisplayedPage] = useState(pages[0]);
const [count, setCount] = useState(0);

   useEffect(() => {
    const timer: ReturnType<typeof setTimeout> = setTimeout(() => {
        const randomNumber = pages[Math.floor(Math.random() * pages.length)];

        if (randomNumber === displayedPage) {
            setCount(count + 1);
            clearTimeout(timer);
            return timer;
        }
        setDisplayedPage(randomNumber);
    }, 5000);

    return () => clearTimeout(timer);

});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

To make everlasting cycles you should use setInterval, to avoid problems with rerenders you can useRef

const pages = [ 'screen1', 'screen2' ];

const [displayedPage, setDisplayedPage] = useState(0);
const [count, setCount] = useState(0);
const timer = useRef()

useEffect(() => {
  const timer.current = setInterval(() => {
    const randomNumber = Math.floor(Math.random() * pages.length);
    setCount(count + 1);
    setDisplayedPage(current => 
      randomNumber == current ? 
        pages[(current+1)%pages.length]
        :
        pages[randomNumber]
    );
  }, 5000);
  return () => clearInterval(timer.current);
});
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!