Search code examples
javascriptreactjssettimeout

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?


Solution

  • 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.