I have a function defined in a component, it start and keeps running when the component is mounted. What happens to the function when the component stops being rendered or dismount?
class MyComponent extends React.Component<> {
_count = () => {
console.log('a second passed');
setTimeout(1000, this._count);
}
componentDidMount() {
_count();
}
}
The timer will keep running unless it gets cleared, so you will want to clear it in componentWillUnmount which is used to "perform any necessary cleanup...such as invalidating timers":
class MyComponent extends React.Component {
_count = () => {
console.log('a second passed');
this.countTimer = setTimeout(this._count, 1000);
}
componentDidMount() {
_count();
}
componentWillUnmount() {
clearTimeout(this.countTimer);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With