Home > other >  How to run a function every x minutes in react
How to run a function every x minutes in react

Time:12-07

My users have the option to run a function every minute, every two minutes or turn it off, altogether, it looks like this...

<select value={runFunctionTime} onChange={e => setRunFunctionTime(e.target.value)}>
  <option value='off'>Off</option>
  <option value='one minute'>One Minute</option>
  <option value='two minutes'>Two Minutes</option>
</select>

This then updates the state. My question is, how do I run a function every x minutes with x being the value they select, if they turn it 'off' then I don't want the function to run at all.

    useEffect(() => {
        let reload = 60

        const autoRefresh = setTimeout(() => {
            if(autoRefreshTime === 'off'){
                reload = 0
            } else if(autoRefreshTime === 'one minute'){
                reload = 60
                RunFunction()
            } else if(autoRefreshTime === 'two minutes'){
                reload = 120
                RunFunction()
            }
        }, reload * 1000)
    })

This didn't work, so does anyone know a way to do this?

CodePudding user response:

It's most probably because autoRefreshTime is not in useEffect dependencies.

Also set reload time outside of timeout's callback, everything in that callback is called after the reload time

This should help, so useEffect knows it should refresh every time autoRefreshTime is changed

useEffect(() => {
        let reload = 0

        if(autoRefreshTime === 'one minute'){
            reload = 60
        } else if(autoRefreshTime === 'two minutes'){
            reload = 120
        }

        if (!reload) {
            return
        }

        const autoRefresh = setInterval(() => {
            RunFunction()
        }, reload * 1000)

       return () => {
          // Clear previous timeout
          clearInterval(autoRefresh)
       }
}, [autoRefreshTime])
  • Related