0

I'm in a component called "recoger_success" and I want it to navigate to the home component after 10 seconds after clicking a button that has countdown() linked to it. The problem is that if I navigate to another component before the timeout gets to 0 then after the 10 seconds it doesn't matter in which component I am, it will always go to home component. I don't want this I want it only to go to the home component if the user is still on the timeout component otherwise ignore it..

I have tryed this to know the url of the actual component but it doesn't work..

countdown(){
  setTimeout(() => {
    if (this.route.snapshot.url.toString() == 'recoger_success'){
        this.router.navigate([""]);
    }
  }, 10000);

}

apreciate any help.

Alex
  • 75
  • 10

2 Answers2

1

Assign timeout to a variable and at the time you manually exist the page, clear the timeout

countdown(){
  this.timeout = setTimeout(() => {
    if (this.route.snapshot.url.toString() == 'recoger_success'){
        this.router.navigate([""]);
    }
  }, 10000);
}

function myStopFunction() {
    clearTimeout(this.timeout);
}
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
  • I feel like this is not the perfect way to do it but works if I use it together with a subscription to know if the route changes then use the mystopfunction router.events.subscribe((val) => { this.myStopFunction(); }); – Alex Jun 07 '18 at 10:34
0

You need to bind the setTimeout to a variable.

component.ts

import { Component, OnDestroy } from '@angular/core';

export class Component implements OnDestroy {

  countdownTimer: any;

  countdown() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
    this.countdownTimer = setTimeout(() => {
      if (this.route.snapshot.url.toString() == 'recoger_success') {
        this.router.navigate([""]);
      }
    }, 10000);
  }


  ngOnDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  }
}
ihist
  • 86
  • 5