I am working on a project and I have added a carousel in it but when I apply this.autoPlay()
then the page is rendered on the browser but just keeps loading ,And nothing was visible on the page, but when I removed this.autoPlay()
the page was working properly, But I need it very much but it is not working, how do I solve this problem.
review my code and give me solution for this
import { Component } from '@angular/core';
import { homeCarouselData } from '../../../Data/mainCarousel';
@Component({
selector: 'app-main-carousel',
templateUrl: './main-carousel.component.html',
styleUrls: ['./main-carousel.component.scss']
})
export class MainCarouselComponent {
carouselData:any;
currentSlide=0;
interval:any;
ngOnInit() {
this.carouselData=homeCarouselData;
this.autoPlay();
}
autoPlay(){
setInterval(()=>{
this.nextSlide();
},2000)
}
nextSlide() {
this.currentSlide=(this.currentSlide+1) % this.carouselData.length;
}
}
1
The problem with your autoPlay()
function seems to be that you are using setInterval()
without properly managing it,
which can cause performance issues or infinite loops, leading to constant page loading.
So what you need to do is cancel setInterval
when the component is destroyed.
You must also add OnDestroy
to the title of the component to implement it, it will look like this:
export class MainCarouselComponent implements OnInit, OnDestroy{}
and also add the following function:
ngOnDestroy() {
// Clearing the interval when the component is destroyed
if (this.interval) {
clearInterval(this.interval);
}
}