useEffect(() => {
const interval = setInterval(() => {
console.log('This will run every second!');
}, 1000);
return () => clearInterval(interval);
}, []);
// don't forget to clean it up:
useEffect(() => {
const interval = setInterval(() => console.log('hello!'), 1000)
return () => clearInterval(interval) // cleanup
}, [])
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);
};
}
timer: function() {
var newCount = this.state.currentCount - 1;
if(newCount >= 0) {
this.setState({ currentCount: newCount });
} else {
clearInterval(this.state.intervalId);
}
},
const render = () => {
document.getElementById('mountNode').innerHTML=
`
<div>
Hello HTML
<input />
<pre>${(new Date).toLocaleTimeString()}</pre>
</div>`;
ReactDOM.render(
React.createElement('div',null,'Hellow World',
React.createElement('input',null),
React.createElement('pre',null,(new Date).toLocaleTimeString())
),
document.getElementById('mountNode2')
);
};
setInterval(render, 1000)