Timers in React Native (this.setTimeout)

Take refrence from @chiquyet , Thank you @chiquyet

https://stackoverflow.com/a/47549754/11754047

this.clearInterval(this.state.timer);

Will throw error in react native

Description

Simple timer in react native with 5 secounds, along with validation and alert

I try in, () => "react": "16.9.0", "react-native": "0.61.5",

Snack Expo Link () => https://snack.expo.io/PuYxRmueW

import React from 'react'
import { View, Text, Button, SafeAreaView, TextInput } from 'react-native'

export default class Timer extends React.Component {

    state = {
        timer: null,
        counter: 5,
    };

    startTimer = () => {

        let timer = setInterval(this.manageTimer, 1000);
        this.setState({ timer });

    }

    manageTimer = () => {

        var states = this.state

        if (states.counter === 0) {
            alert('Times Up !\nTimer  is reset')
            clearInterval(this.state.timer)
            this.setState({
                counter: 5
            })
        }
        else {
            this.setState({
                counter: this.state.counter - 1
            });

        }
    }

    componentWillUnmount() {
        clearInterval(this.state.timer);
    }



    render() {
        return (
            <SafeAreaView>


                <Text style={{ textAlign: 'center' }}>{this.state.counter}</Text>

                <View>
                    <Button
                        title='START TIMER'
                        onPress={() => this.startTimer()}
                    />
                </View>
            </SafeAreaView>
        )
    }
}

Hope this will help you :)


Settimeout and setInterval still work in react-native. BUT you have to use it in the right way:

Here is one of many ways to implement a timeout in React that I'm usually used:

export default class Loading extends Component {
  state = {
    timer: null,
    counter: 0
  };

  componentDidMount() {
    let timer = setInterval(this.tick, 1000);
    this.setState({timer});
  }

  componentWillUnmount() {
    clearInterval(this.state.timer);
  }

  tick =() => {
    this.setState({
      counter: this.state.counter + 1
    });
  }

  render() {
    return <div>Loading{"...".substr(0, this.state.counter % 3 + 1)}</div>
  }
}

With this approach you don't have to worry about memory leak anymore. Just simple and straight forward.

There is an excellent article talking about this; you can refer to it here: https://medium.com/@machadogj/timers-in-react-with-redux-apps-9a5a722162e8


For the sake of also adding what it would look like with functional component and hooks.

import React, { useEffect } from 'react'
import { Text } from 'react-native'

const Component = props => {

    useEffect(() => {
        let timer = setInterval(() => console.log('fire!'), 1000);

        return () => clearInterval(timer)
    }, [])

    return <Text>Example of using setInterval with hooks</Text>
}