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

118
Views
Different intervals for setTimeout in useEffect

I am trying to achieve a situation when a function inside setTimeout is executed after X seconds first time, and then regularly at Y interval.

    useEffect(() => {
    let firstTime = true;
    const timer = setTimeout(() => {
      getValue(id).then((res) => {
        setValue(res);
      });
      if (firstTime) {
        firstTime = false;
      }
    }, firstTime ? 30000 : 60000);
    return () => clearTimeout(timer);
  }, [])

This doesn't work, however, as it sets firstTime to false before running the function. Is there a way to graciously achieve the result? Is it even possible with setTimeout?

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

0

You can use a variable as the setTimeout delay. In this case you would set firstTime to the delay you wanted to use the first time (30000), and then inside timer you would use if (firstTime == 30000) { firstTime = 60000; }. Using a different variable name here would make sense. Then set the setTimeout delay to just firstTime like }, firstTime);

Hopefully this is actually what you wanted.

useEffect(() => {
    let firstTime = 30000;
    const timer = setTimeout(() => {
      getValue(id).then((res) => {
        setValue(res);
      });
      if (firstTime == 30000) {
        firstTime = 60000;
      }
    }, firstTime);
    return () => clearTimeout(timer);
  }, [])

Old (incorrect) answer:

You can use setTimeout with an initial delay to initialise a setInterval, which will repeat subsequent times at a different interval.

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!