Home > Mobile >  How to set interval in react js first time 0 sec after that 30 sec?
How to set interval in react js first time 0 sec after that 30 sec?

Time:10-11

How to set interval in react js first time 0 sec after that 30 sec?

//this is my state
  const [state, setState] = useState();
  useEffect(() => {
    const interval = setInterval(() => {
      APiResponse();
    }, 30000);
    return () => clearInterval(interval);
    `enter code here`;
  }, []);

  const APiResponse = () => {
    axios.get(`xxx`).then((res) => {
      setState(res);
    });
  };

CodePudding user response:

Set a timer variable in a setTimeOut method above your method to zero that once the component is rendered the useEffect life cycle will be called and after doing your call set it to whatever you need;

let interval;
setTimeout(()=>{

  APiResponse(); // first time zero

 interval = setInterval(() => {
  APiResponse(); // after 30 second

 } ,  30000);
}, 0)

CodePudding user response:

You can use a setTimeout for the first time. Then with a flag state variable that is updated after the first render, you can start your interval.

  const [state, setState] = useState();
  const [flag, setFlag] = useState(false);
  
useEffect(() => {
    const interval = setTimeout(() => {
     APiResponse();
    }, 0);
    `enter code here`;
  });

  useEffect(() => { if(flag === true){
   const interval = setInterval(() => {
      APiResponse();
    }, 30000);
    return () => clearInterval(interval);
  }
  },[flag]);

  const APiResponse = () => {
    setFlag(true);
    axios.get(`xxx`).then((res) => {
      setState(res);
    });
  };

CodePudding user response:

You can use the code below, the idea is to invoke the setInterval callback function immediately for once and 30 sec intervals after that. Note that its an IIFE. so it wont push to task queue, instead it immediately triggers (no delay).

const [state, setState] = useState();
  useEffect(() => {
    const interval = setInterval(
      (function callApi() {
        APiResponse();
        return callApi;
      })(),
      30000
    );
    return () => clearInterval(interval);
  }, []);

  const APiResponse = () => {
    axios.get(`xxx`).then((res) => {
      setState(res);
    });
  };

I have named the function callApi.The return callApi; line returns the same function, we can call it immediately as well as use this as a callback function to setInterval.

  • Related