Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neither setInterval nor setTimeout works react-native ES6

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);

enter image description here enter image description here

like image 219
cube Avatar asked Aug 10 '16 00:08

cube


1 Answers

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);
}
like image 82
Jeremie Avatar answered Nov 03 '22 18:11

Jeremie