Skip to content
Advertisement

I need to create a delay for text2 in my react component

As the title suggests. You can see in my code, I have text and text2 that forms the text for the typing effect. But they both start at the same time. I would like to create a delay on text2 so that it starts when text finishes. Any help would be greatly appreciated and thank you in advance.

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text:"This is sample text",
      text2:"This is sample text for text2",
      count:0,
      show:"",
      show2:"",
    }
    this.update = this.update.bind(this);
  }
  
  componentDidMount() {
    this.timerID = setInterval(
      () => this.update(),
      300
    );
  }
  
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
  
  update(){
    const counter = this.state.count;
    const letter = this.state.text.charAt(counter);
    const letter2 = this.state.text2.charAt(counter);
    const textlength = this.state.text.length;
    //let text += letter;
    console.log("counter : " + counter + " / letter : " + letter);
    console.log("counter : " + counter + " / letter2 : " + letter2);
    
    if(counter <= textlength){
    this.setState({
      show: this.state.show + letter,
      show2: this.state.show2 + letter2,
      count: this.state.count + 1,
    });
    }else{
      clearInterval(this.timerID);
    }
  };

Advertisement

Answer

Here you go

update() {
  const counter = this.state.count;
  const text1 = this.state.text;
  const text2 = this.state.text2;
  const letter = text1.charAt(counter);
  // Note: It'll be empty string for negative index
  const letter2 = text2.charAt(counter - text1.length);
  const textlength = text1.length + text2.length;

  if(counter < textlength) {
    this.setState({
      show: this.state.show + letter,
      show2: this.state.show2 + letter2,
      count: this.state.count + 1,
    });
  } else {
    clearInterval(this.timerID);
  }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement