I have a react application that needs to display some text with different interval between the sentences, one at a time.
So what I did is to put all the sentences in an array and create a setInterval function:
startShowingText() {
let i = 0
this.setState({
timer: window.setInterval(() => {
this.setState({
sentence: SENTENCES[i]
})
i += 1
}, this.state.startingDuration)
})
}
Unfortunately this approach has many downside:
1) It needs a check to terminate;
2) I can't modify the time dynamically, so once this.state.startingDuration is set, that's going to be the speed for all the sentences...
3) For some reasons, if I assign the window.setInterval function to a variable outside the state, that piece of code is not executed:
startShowingText() {
let i = 0
console.log('here')
const timer = window.setInterval(() => {
this.setState({
sentence: SENTENCES[i]
})
i += 1
}, this.state.startingDuration)
console.log('there')
}
This code was just printing:
here
there
Without triggering the actual timer.
How can I improve the code and make the interval dynamically adjustable?