While you could use setTimeout
as shown in the other answer to induce an implicit delay, here is an implementation using RxJS timer
function that implicitly "pauses" and iterates every 2 seconds.
import { Component, OnInit, OnDestroy } from "@angular/core";
import { timer, Subject } from "rxjs";
import { tap, take, takeUntil } from "rxjs/operators";
@Component({ ... })
export class AppComponent implements OnInit, OnDestroy {
countUser: number = 200;
closed$ = new Subject<any>();
ngOnInit() {
this.test();
}
test() {
timer(0, 2000) // (1)
.pipe(
tap({ next: _ => this.countUser-- }), // (2)
take(this.countUser), // (3)
takeUntil(this.closed$) // (4)
)
.subscribe({
next: count => {
console.log(count);
// do something else here
}
});
}
ngOnDestroy() {
this.closed$.next(); // (5)
}
}
Breakdown
- Emit a notification immediately and every 2 seconds thereafter.
- Decrement the iteration counter by 1 for every emission of the observable.
- Emit only specific number of times specified by the step 2.
- Close the subscription if the component is closed prematurely. Helps avoid memory leak.
- Close open subscriptions when the component is closed.
Working example: Stackblitz