Marko Kos
Marko Kos

Reputation: 33

Change timeout duration

I am building Angular 6 app where I have multiple items and each item have some configuration. On each item I defined duration how long this item must be visible.

I created this, but I am interested if this can be written in rxjs or maybe if there is simpler solution.

const timer = () => {
    this.counter++;
    this.currentItem = this.items[this.counter % this.items.length];
    setTimeout(timer, this.currentItem.duration);
};
setTimeout(timer, this.currentItem.duration);

Upvotes: 2

Views: 166

Answers (1)

martin
martin

Reputation: 96979

With RxJS 6 you could do something like this

from(items)
  .pipe(
    concatMap(item => of(null) // Wait until the previous inner observable completes
     .pipe(
       delay(item.duration), // Delay emission after this value
       ignoreElements(),
       startWith(item),
     )
    ),
    repeat(),
  )
  .subscribe(console.log);

See live demo: https://stackblitz.com/edit/rxjs6-demo?file=index.ts

Upvotes: 1

Related Questions