I have a React project where I am trying to build a carousel. I have both a button left and right and some circles under my carousel to select slides individually.
To change the slides in the carousel I am using a combination of intervals and timeouts to play a slide animation as well as to make sure it runs in a loop if the user does not click anything:
changeImageTimer(index = 0) {
end = new Date().getMilliseconds();
console.info(end - start);
setTimeout(()=> {
this.addAnimation();
}, this.props.timeToChangeImage - this.props.timeOfTransitionAnimation);
animationTimeout = setTimeout(() => {
if (this.state.index >= this.props.data.length - 1) {
index = 0;
} else {
index = this.state.index + 1;
}
this.setState({index: index});
this.removeAnimation();
}, this.props.timeToChangeImage);
animationInterval = setInterval(() => {
setTimeout(()=> {
this.addAnimation();
}, this.props.timeToChangeImage - this.props.timeOfTransitionAnimation);
animationTimeout = setTimeout(() => {
if (this.state.index >= this.props.data.length - 1) {
index = 0;
} else {
index = this.state.index + 1;
}
this.setState({index: index});
this.removeAnimation();
}, this.props.timeToChangeImage);
}, this.props.timeToChangeImage);
}
The buttons to select an individual slide have this function attached:
clickSelector(index) {
this.clearIntervalsAndTimers();
this.setState({index: index});
start = new Date().getMilliseconds();
timeout = setTimeout(this.changeImageTimer(index), this.props.timeToHoldPictureAfterClick);
}
As you can see, I want the slide to stay and then after some time restart the automatic iteration of slides.
However, the 'changeImageTimer' code is run immediately after the 'clickSelector' function and is not run after the set timeout delay.
Why do I have this behavior?