Reputation: 1079
I have an image slider using Vue.js with a setInterval function looping through 4 images, I have it working almost to my liking except on the last image clearInterval call there is too long of a delay before the image slider starts again on the 0 image index. Is there a way to go directly back to the first index / image smoother / quicker?
<script>
export default {
name: "Slider",
data() {
return {
currentSliderIndex: 0
};
},
mounted() {
setInterval(() => {
this.currentSliderIndex = this.currentSliderIndex + 1;
if (this.currentSliderIndex > 4) {
clearInterval();
this.currentSliderIndex = 0;
}
}, 4000);
}
};
</script>
Upvotes: 2
Views: 1226
Reputation: 1140
It doesn't look like you need to call clearInterval
, which isn't doing anything in this case because you aren't passing the ID of your interval (as Peter Wolf points out in the comments).
Your problem is that you are only resetting the currentSliderIndex
if currentSliderIndex > 4
. You need to check if currentSliderIndex > 3
, because index 4 will be the 5th element in your array of images. Try this instead:
<script>
export default {
name: "Slider",
data() {
return {
currentSliderIndex: 0
};
},
mounted() {
setInterval(() => {
this.currentSliderIndex = this.currentSliderIndex + 1;
if (this.currentSliderIndex > 3) {
this.currentSliderIndex = 0;
}
}, 4000);
}
};
</script>
Upvotes: 1