-1

I have a loop but I want the loop to pause for 2 seconds each time the loop is run and then move on to the next round, how do I do that?

Example:

countUser:number = 200;
countMe:number = 0;

test() {
  for(let i = 0; i < this.countUser; i++){
    this.countMe +=1; 
    // Stop for two seconds, then run the next round of the loop
  }
}

typescript: ~3.7.5

Striped
  • 2,352
  • 3
  • 21
  • 28
Aliakbar
  • 68
  • 1
  • 8
  • Does this answer your question? [Add a delay after executing each iteration with forEach loop](https://stackoverflow.com/questions/45498873/add-a-delay-after-executing-each-iteration-with-foreach-loop) – Sourav Dutta Nov 08 '20 at 08:58

2 Answers2

1

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

  1. Emit a notification immediately and every 2 seconds thereafter.
  2. Decrement the iteration counter by 1 for every emission of the observable.
  3. Emit only specific number of times specified by the step 2.
  4. Close the subscription if the component is closed prematurely. Helps avoid memory leak.
  5. Close open subscriptions when the component is closed.

Working example: Stackblitz

Michael D
  • 20,838
  • 4
  • 12
  • 37
0

Perhaps easiest way to do:

countUser:number=200;
countMe:number=0;
test(){
  for(let i=0;i<this.countUser;i++){
   // Pause for 2 seconds then increment countMe, move to next loop
   setTimeout(function(){
    this.countMe +=1; 
   }, 2000);
  }
}
unobatbayar
  • 868
  • 6
  • 20