-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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.