Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  41] [ 6]  / answers: 1 / hits: 14938  / 4 Years ago, tue, july 28, 2020, 12:00:00

Im having a lot of trouble with this and i have tried various things. I want to call a function every second after i have clicked a start button and then have it paused after i click a stop button. I keep getting weird behaviour that i cant explain.
How can i do this in react without classes?


somethings i have treid:


      const simulation = () => {
if (!running) {
console.log('hit');
return

} else {
// console.log(grid);
console.log('hey');
setTimeout(simulation, 1000)
}
}

and


    enter  setInterval(() => {
let newGrid = [...grid]
for (let i = 0; i < numRow; i++) {
for (let k = 0; k < numCol; k++) {
let n = 0;
}
}
console.log(grid);
}, 5000)

I have tried a lot more, In some cases it would update the state should i have added to it but not updated it after i reset the state.
How can i call a function to run every one second with updated values of state * Note the function that i want to run will update the state


More From » reactjs

 Answers
2

You may do the following:



  • keep track of the current counter value along with the counter on/off state in your component state;

  • employ useEffect() hook to be called upon turning counter on/off or incrementing that;

  • within useEffect() body you may call the function, incrementing count by one (if ticking is truthy, hence timer is on) with delayed execution (using setTimeout());

  • once count variable is changed in the state, useEffect() gets called once again in a loop;

  • in order to clean up the timer upon component dismantle, you should return a callback, clearing the timer from useEffect()




const { useState, useEffect } = React,
{ render } = ReactDOM,
rootNode = document.getElementById('root')

const App = () => {
const [ticking, setTicking] = useState(true),
[count, setCount] = useState(0)

useEffect(() => {
const timer = setTimeout(() => ticking && setCount(count+1), 1e3)
return () => clearTimeout(timer)
}, [count, ticking])

return (
<div>
<div>{count}</div>
<button onClick={() => setTicking(false)}>pause</button>
<button onClick={() => setTicking(true)}>resume</button>
</div>
)
}

render (
<App />,
rootNode
)

<script src=https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js></script><div id=root></div>




[#3040] Sunday, July 26, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
turnerf questions
;