Anthony Barrault
Anthony Barrault

Reputation: 47

Is there any way to display <Text> with a timer setTimeout() multiple times?

I'm trying to return 9 differents Text with a 5 seconds delay between each ones but it's only working for the first Text

i've tried using

  render() {
    setTimeout(() => {this.setState({timePassed: true})}, 2000);
    if(this.state.timePassed == false){
      return (
        <Text></Text>
      )
    }else if (this.state.timePassed == true{
      return(
        <Text>HELLO</Text>
      )
    }else if (this.state.timePassed1 == false{
............
  }
}

but not working I have also tried

  componentDidUpdate(){
    setTimeout(() => {this.setState({timePassed1: true})}, 4000);
    if(this.state.timePassed1 == true){
      return(
      <Text>test</Text>)
    }
}

but not working

Here is my screen

export default class Internet2 extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      timePassed: false,
      timePassed1: false
    };
  }

  componentDidUpdate(){
    setTimeout(() => {this.setState({timePassed1: true})}, 4000);
    if(this.state.timePassed1 == true){
      return(
      <Text>test</Text>)
    }
}

  render() {
    setTimeout(() => {this.setState({timePassed: true})}, 2000);
    if(this.state.timePassed == false){
      return (
        <Text></Text>
      )
    }else{
      return(
        <Text>HELLO</Text>
      )
    }
  }
}

Thank you for your help !

Upvotes: 0

Views: 1354

Answers (2)

Vencovsky
Vencovsky

Reputation: 31713

What you can do is keep the texts in an array and a variable for counting how many times has it passed.

state = {
    texts = ['sometext', ...]
    textCount = 0
}

Then you will create a setInterval to loop in the time you want

componentDidMount() {
    let timer = setInterval(() => {
        this.setState(prevState => {
            return {textCount: prevState.textCount + 1}
        })
        if (this.state.textCount > this.state.texts.length) clearInterval(timer);
    }, theTimeYouWant);
}

And render the texts using .map

  render() {
      return (
        <View>
            {this.state.texts.map((text, i) => i <= this.state.textCount ?
               <Text>{text}</Text> : null
            )}
        </View>
      )
  }

Upvotes: 1

Anthony Barrault
Anthony Barrault

Reputation: 47

I found the solution, its in render and you have to go like:

  constructor(props){
    super(props);
    this.state = {
      timePassed: false,
      timePassed1: false
    };
  }

  render() {
    setTimeout(() => {this.setState({timePassed: true})}, 2000);
    setTimeout(() => {this.setState({timePassed1: true})}, 3000);
      return (
        <View>
        {this.state.timePassed == true ? (<Text>INTERNET</Text>) : null}
        {this.state.timePassed1 == true ? (<Text>TEST</Text>) : null}
        </View>
      )

  }
}

Upvotes: 0

Related Questions