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

147
Views
why cleanup function dos not work in react app

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(() => {
                clearInterval(time)
                dispatch(getNameStep(states.step))
            }, 60000);
  } else {
    return
  }
}
useEffect(() => {
    timeDown()
    return () => {
      console.log('unmounted')
      timeDown()
    }
  }, [])
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

time is not a timeout but an interval:

clearTimeout(time) ⇨ clearInterval(time)

about 4 years ago · Juan Pablo Isaza Report

0

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()
    }
  }, [])
about 4 years ago · Juan Pablo Isaza Report

0

https://medium.com/@monica1109/scheduling-settimeout-and-setinterval-ca2ee50cd99f#:~:text=The%20only%20difference%20is%20%2C,should%20call%20clearInterval(timerId)%20. This blog clearly explains the difference between settimeout & setInterval

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!