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.
JavaScript
x
44
44
1
class Home extends Component {
2
constructor(props) {
3
super(props);
4
this.state = {
5
text:"This is sample text",
6
text2:"This is sample text for text2",
7
count:0,
8
show:"",
9
show2:"",
10
}
11
this.update = this.update.bind(this);
12
}
13
14
componentDidMount() {
15
this.timerID = setInterval(
16
() => this.update(),
17
300
18
);
19
}
20
21
componentWillUnmount() {
22
clearInterval(this.timerID);
23
}
24
25
update(){
26
const counter = this.state.count;
27
const letter = this.state.text.charAt(counter);
28
const letter2 = this.state.text2.charAt(counter);
29
const textlength = this.state.text.length;
30
//let text += letter;
31
console.log("counter : " + counter + " / letter : " + letter);
32
console.log("counter : " + counter + " / letter2 : " + letter2);
33
34
if(counter <= textlength){
35
this.setState({
36
show: this.state.show + letter,
37
show2: this.state.show2 + letter2,
38
count: this.state.count + 1,
39
});
40
}else{
41
clearInterval(this.timerID);
42
}
43
};
44
Advertisement
Answer
Here you go
JavaScript
1
20
20
1
update() {
2
const counter = this.state.count;
3
const text1 = this.state.text;
4
const text2 = this.state.text2;
5
const letter = text1.charAt(counter);
6
// Note: It'll be empty string for negative index
7
const letter2 = text2.charAt(counter - text1.length);
8
const textlength = text1.length + text2.length;
9
10
if(counter < textlength) {
11
this.setState({
12
show: this.state.show + letter,
13
show2: this.state.show2 + letter2,
14
count: this.state.count + 1,
15
});
16
} else {
17
clearInterval(this.timerID);
18
}
19
}
20