I have the following method in one component:
ngOnInit()
{
this.battleInit();
setInterval(() => {
this.battleInit();
}, 5000);
}
Now, I need to run this interval only if the user is in this specific component, that means that when the user navigate away from this component the interval will stop.
Currently, this.battleInit()
is executed every 5 seconds, even after the user navigates away from this page.
Short question: How do I stop setInterval()
when user navigate away (by routing) to another component?
You need to use clearInterval
method for this within the ngOnDestroy
hook method of your component. For this you need to save the returned value by the setInterval
method.
Here is a sample:
ngOnInit() {
this.battleInit();
this.id = setInterval(() => {
this.battleInit();
}, 5000);
}
ngOnDestroy() {
if (this.id) {
clearInterval(this.id);
}
}
below code are write <br>
ngOnInit() {
this.battleInit();
this.id = setInterval(() => {
this.battleInit();
}, 5000);
}
ngOnDestroy() {
if (this.id) {
clearInterval(this.id);
}
}
this.id means number of iteration it triggered
every 40 seconds
polling: any;
ngOnInit() {
this.consulta();
this.pollData();
}
pollData () {
this.polling = setInterval(() => {
this.consulta();
},40*1000)
ngOnDestroy() {
clearInterval(this.polling);
}