I'm trying to get a basic timer going in react-native, but it's not working. I get no errors in the console. It just simply ignores the setInterval
. I read the TimerMixin issue with ES6 (not supported). So what is the alternative if you want to use just a basic setInterval
timer?, as it simply does not work in its simplest form shown here...
import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
class HelloWorldApp extends Component {
componentDidMount() {
console.log('COMPONENTDIDMOUNT')
//this.timer= <--//This doesn't work either
var timer = setInterval(() => {
console.log('I do not leak!');
}, 5000);
}
componentWillUnmount() {
console.log('COMPONENTWILLUNMOUNT')
clearInterval(timer);
}
render() {
return (
<Text>Hello world!</Text>
);
}
}
AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);
You need to save the time as an instance variable and clear it on component unmount. Example:
componentDidMount() {
this._interval = setInterval(() => {
// Your code
}, 5000);
}
componentWillUnmount() {
clearInterval(this._interval);
}
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