0

I want to display an array of slides and each slide has a value which tells the programm how long it should be displayed for. Since the slides are stored in an array I thought about just looping through the array, display the current slide and then just wait the amount of time at the end before looping again.

So this is my attempt:

for (let  i= 0; i < this.slides.length; i++) {
  setTimeout(() => {
    this.currentSlide = this.slides[i]
  }, this.slides[i].slidetime * 1000);
}

I even tried doing it like this:

for (let  i= 0; i < this.slides.length; i++) {
  this.currentSlide = this.slides[i];
  this.wait(this.slides[i].slidetime);
}

wait(seconds) {
  setTimeout(() => {}, seconds * 1000);
}

But it didn't make a difference.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
niehoelzz
  • 385
  • 5
  • 20

2 Answers2

1

You used the tag angular so you can use Observables for this:

from(this.slides).pipe(
  concatMap((slide) => of(slide).pipe(
    tap((slide) => this.currentSlide = slide),
    delay(slide.slideTime)
  ))
).subscribe()

If observables are a bit too tricky for you, you can use the await/async method:

async goThroughSlides(): Promise<void> {
  for (let i = 0; i < this.slides.length; i++) {
    this.currentSlide = this.slides[i];
    await new Promise((resolve) => setTimeout(resolve, this.currentSlide.slideTime));
  }
}

I made an example stackblitz

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
-1

create another variable that will hold the values for slides and use it in your html.

newSlides: any;

for(let i = 0; i < this.slides.length; i++){
        let slide = this.slides[i];
        setTimeout(() => {
            this.newSlides.push(slide);
        }, 2000*(i+1));
    }
Poldo
  • 1,924
  • 1
  • 11
  • 27