Search code examples
angulartypescriptsettimeoutcleartimeout

setTimeout continues when user route to different page, how to clearTimeout in angular typscript?


I used setTimeout to jump to the upload page after 10 seconds. But the timeout continues when user navigate to another page. I followed the instructions on this link(Angular 2 setinterval() keep running on other component) and added clearTimeout to ngOnDestroy, but it does not work.

  ngOnInit() {
    
    // Get uploaded file info
    this.uploadService.getFileInfo().subscribe((value) => {
      this.fileInfo = value;
    

      this.http.post(environment.apiUrl+'/api/dataValidation/validateData.php', this.fileInfo)
        .subscribe(res => {
          console.log('response'+res)
          if (res['length']<5) {
            
            //console.log(res);
            this.failure = true;
            this.fileValidationResults.errorMessage =res[0];
            this.loading = false; // stop loading screen
            this._timer =setTimeout(() => {
              this.router.navigate(["/uploads/upload"]);
            }, 10000); 
          }
        })
    });

  }
  ngOnDestroy() {
    if (this._timer){
      clearTimeout(this._timer);
  };
  }

How can I stop setTimeout() when user navigate to another link and let setTimeout() only works in it's own component?


Solution

  • Should work, remember when declare your component implements OnDestroy

    BTW, You can use timer operator of rxjs instead of setTimeout

    import {timer} from 'rxjs'
    import {takeWhile} from 'rxjs/operators'
    ...
    
    export class OneComponent implements OnInit,OnDestroy {
    
       alive:boolean=true;
    
       ngOnInit(){    
         timer(1000).pipe(takeWhile(()=>this.alive)).subscribe(_=>{
            this.router.navigate(['/three'])
         })
       }
    
       ngOnDestroy()
       {
           this.alive=false;
       }
    }