Home > front end >  why cleanup function dos not work in react app
why cleanup function dos not work in react app

Time:10-05

timer dos not stop after we go into another component and then loser component will runing but i can see unmounted in console. i mean want to cleanup timer function like componentWillUnmount in class components.

function timeDown() {
  if (stepName == 'question') {
    let haveTime = state.haveTime;
    let time = setInterval(() => {
        haveTime -= 1;
        setState({ haveTime })
      }, 1000);
    setTimeout(() => {
        clearTimeout(time)
        dispatch(getNameStep(states.step))
      }, 60000);
  } else {
    return
  }
}
useEffect(() => {
    timeDown()
    return () => {
      console.log('unmounted')
      timeDown()
    }
  }, [])

CodePudding user response:

time is not a timeout but an interval:

clearTimeout(time)clearInterval(time)

CodePudding user response:

There's two kinds of "timer" functions. setInterval() and setTimeout(). Note that each of these have their respective clear functions.

When you make a timer using setInterval(), you must clear it with clearInterval(), same for setTimeout() and clearTimeout().

time, in your example, is an interval. The following code should work:

function timeDown() {
  if (stepName == 'question') {
    let haveTime = state.haveTime;
    let time = setInterval(() => {
        haveTime -= 1;
        setState({ haveTime })
      }, 1000);
    setTimeout(() => {
        clearInterval(time)
        dispatch(getNameStep(states.step))
      }, 60000);
  } else {
    return
  }
}

useEffect(() => {
    timeDown()
    return () => {
      console.log('unmounted')
      timeDown()
    }
  }, [])
  • Related