Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

setinterval react

let myCounter = 0;
let timeout = null;
export default CounterApp = props => {

  const [counter, setCounter] = useState(0);

  // Also don't forget this
  useEffect(()=> {
    return ()=> clearInterval(timeout);
  }, []);      

  myCounter = counter;
  const startInterval = () => {
    timeout = setInterval(() => {
      setCounter(counter => counter + 1);
      console.log("counter: ", myCounter); // counter always return 0 but myCounter the updated value
      if(myCounter === 10) clearInterval(timeout);

    }, 1000);
  };

}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #setinterval #react
ADD COMMENT
Topic
Name
5+1 =