logo
Tags down

shadow

not able to clear Interval using variable which is outside the react hook


By : Amir
Date : July 29 2020, 07:08 AM
fixed the issue. Will look into that further If you need to save variables across re-renders use useRef which in this case acts like a class instance field, also note that mutations to refs does not trigger a re-render.
This will give you the ability to clear the interval from outside of useEffect
code :
function Child(props) {
  let [timerCount, setTimer] = useState(0)
  const intervalRef = useRef(null)

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setTimer(prevState => prevState + 1)
    }, 1000)

    return () => clearInterval(intervalRef.current)
  }, [])

  function clearTimer() {
    clearInterval(intervalRef.current)
    intervalRef.current = null
  }

  return (
    <div>
      <div>Timer {timerCount}</div>
      <button onClick={clearTimer}>ClearTimer</button>
    </div>
  )
}


Share : facebook icon twitter icon

Clear interval in React class


By : Jake Brain
Date : March 29 2020, 07:55 AM
Any of those help You need to store the interval reference returned from setInterval.
From the docs:
code :
this.interval = setInterval(() => {...
 clearInterval(this.interval);
this.interval = setInterval(() => {
      this.setState(prevState => ({
        countDown: prevState.countDown - 1,
      }), () => {
        if (this.state.countDown === 0) {
          this.stopCountDown();
        }
      });
    }, 1000)
class TestInterval extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      countDown: this.props.countDown, // An integer from father component
    }
  }

  timer = () => {
    this.interval = setInterval(() => {
      this.setState(prevState => ({
        countDown: prevState.countDown - 1,
      }), () => {
        if (this.state.countDown === 0) {
          this.stopCountDown();
        }
      });
    }, 1000)
  }

  startCountDown = () => {
    this.timer();
  }

  stopCountDown = () => {
    clearInterval(this.interval); // Not working
  }

  render() {
    return (
      <div>
        <button onClick={this.startCountDown}>
          Start Countdown
                    </button>
        <p>{this.state.countDown}</p>
      </div>
    );
  }
}

ReactDOM.render(<TestInterval countDown={3} />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

React functional component: clearInterval() does not clear my interval


By : user2585509
Date : March 29 2020, 07:55 AM
To fix the issue you can do I think the problem is with how you store the interval id. when using function components and we want to store "instance" variables we can use the useRef hook.
code :
   let intervalId = useRef(null)

  let handlePlayPause = () => {
    debugger
    if (!isRunning) {
      setTimeLeft(sessionLength * 60 * 1000)
      playTimer()
    } else if (isRunning) {
      pauseTimer()
    }
  }

  let playTimer = () => {
    setIsRunning(true)
    intervalId.current = setInterval(() => {
      console.log('interval')
      setTimeLeft(timeLeft => timeLeft - 1000)
      parseToMinuteSeconds(timeLeft)
    }, 1000)
  }


  let pauseTimer = () => {
    setIsRunning(false)
    clearInterval(intervalId.current)
  }

Is useRef Hook a must to set and clear intervals in React?


By : Lukas Tines
Date : March 29 2020, 07:55 AM
To fix the issue you can do As stated at the docs you shared;
code :
  useEffect(() => {
    const id = setInterval(() => {
      setCounter(prev => prev + 1);
    }, 1000);
    return () => {
      clearInterval(id);
    };
  });
// ...
function handleCancelClick() {
  clearInterval(intervalRef.current);
}
  // ...

Does clearing timeout/interval have to be inside `useEffect` react hook?


By : user3312213
Date : March 29 2020, 07:55 AM
I wish this helpful for you You must be sure to clear all intervals before your component gets unmounted. Intervals never disappear automatically when components get unmounted and to clear them, clearInterval is often called inside useEffect(() => {}, []).
The function retured in useEffect(() => {}, []) gets called when the compoment is unmounted.
code :
    return () => {
      clearInterval(id.current)
    }

Clear Interval on hover React


By : Ratcatcher
Date : March 29 2020, 07:55 AM
Hope that helps clearInterval accepts the result of setInterval which you had added to the component state in componentDidMount.
Related Posts Related Posts :
  • Why doesn't the .remove() method also affect the variable it's being set on?
  • React hooks error: Rendered more hooks than during the previous render
  • How to create a completely new Keyword in JavaScript?
  • When summing values from 2 arrays how can I cap the value in the new array?
  • A pop up window to login in
  • How to push spacebar action to array
  • How do i highlight a specific table row depending on the url
  • Truly Weak Reference Event Emitter / Dispatcher: is it possible?
  • Conditionally render a a background image based on current view using React Router
  • Can not retrieve component template while routing
  • How to keep the checkbox status after refreshing the page
  • Array of Object - divide information as per values in it
  • Calculating body style height (for horizontal scroll) in javascript not working
  • How to exclude certain values from randomly generated array
  • Change colour of selected <li>
  • Formatting date object in an Array with moment is giving an unexpected result
  • combineLatest operator alternative
  • 'object' is never reassigned. Use 'const' instead
  • What does the spread operator in ES6 convert to in older JavaScript? Is it costlier than array.concat?
  • Get duplicates in array of strings and count number of duplicates
  • How to fix React Redux and React Hook useEffect has a missing dependency: 'dispatch'
  • Call a ajax request only if there are ajax requests added to the list
  • Using the jQuery each function to count divs with the same class
  • FInding out the Harshad number
  • angular route is not working and not changing current view
  • Callback executed before function finishes execution
  • How to create subfolder and document on Firestore web?
  • Scroll algorithm -- improving fetch and display of data
  • New To Programming World
  • Using mongorestore to insert many documents into a temp collection
  • How to extend localStorage across devices (without DB)
  • How to do pre increment without using ++I?
  • Retrieve filterViewId from batchUpdate request addFilterView
  • What is the corresponding instanceof target for text nodes?
  • How to Test the API by Token on Postman?
  • How to set Bootstrap dropdown menu on hover?
  • In Slate.js editor.apply(operation) is not applying "split_node" operations correctly
  • No data in GET response
  • Javascript using if else to determine array value
  • Error when I run npm install Error: 404 Not Found: 7zip-bin@~4.1.0
  • I want to modified my JSON output using JS
  • Error in Entry module not found and in webpack
  • Submit button is not submitting the form after changing the button type
  • Why is the function created is not working.?
  • How can I do day timer with javascript?
  • Tap screen to trigger autofocus with getUserMedia
  • Unable to bind html table data to mvc controller Model
  • How can I simply work around a missing JS property in an object in an object?
  • How to add anything at a specific position in a string using vanilla javascript
  • using async methods inside of array.map() in javascript
  • Math.random() vs random() in Khan Academy Computer Programming
  • Call two functions with onPress in react native
  • Use a global variable inside promise javascript
  • Turn array of objects into array of properties
  • Would having a Pure Class concept make sense or not?
  • Why catch invoked with success promise?
  • Match whole word if it meets a condition
  • Inserting items into array with bracket syntax doesnt affect length?
  • adding value inside an input - React
  • How does setInterval() run independently of sequential execution?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org