Angular 4 setTimeout does not wait

Viewed 71565

I am creating an angular 4 app with typescript.

I'm having a function that needs to be executed every 10 seconds untill a specified stopcondition. I created a loop with some testcode using setTimeout to see if it would work.

My Testcode:

public run() {
    let i = 0;
    while (i < 4) {
        setTimeout(this.timer,3000);
        i++;
    }
}

public timer(){
    console.log("done")
}

However this seems to wait for 3 seconds, or browser is just slow... and then it prints 4 times done. So the code isn't working. Am I doing this wrong or are there other possibilities to do this kind of things?

7 Answers

I did it with Angular 6. This code requests every 5 seconds to get the progress of rendering. It will stops sending request when the progress reaches %100.

import {interval} from "rxjs";

getProgress(searchId): void{
const subscription = interval(5000)
  .subscribe(()=>{
    //Get progress status from the service every 5 seconds
    this.appService.getProgressStatus(searchId)
      .subscribe((jsonResult:any)=>{
          //update the progress on UI 

          //cancel subscribe until it reaches %100
          if(progressPercentage === 100)
            subscription.unsubscribe();
        },
        error => {
          //show errors
        }
      );
  });
}

Use the function setInterval(hander:(args:any[]),ms:Number,args:any[]) which is one of the methods of OnInit.

setInterval(a=>{
  alert("yes....");
},10000,[]);

Will show alert "yes" after 10 secs.

Related