In my component, there is a recurring interval set up:
export class FoobarComponent implements OnInit {
ngOnInit(): void {
this.startInterval();
}
startInterval() void {
setInterval(() => { console.log('Hi'); }, 1000);
}
}
Every time the component is called, a new interval is created, adding to the existing ones.
I attempted to use an ID (similar to what I used to do with plain JS) like this:
export class FoobarComponent implements OnInit {
intervalId: Number;
ngOnInit(): void {
this.startInterval();
}
startInterval() void {
if(this.intervalId) { // always undefined
window.clearInterval(this.intervalId);
}
this.intervalId = window.setInterval(() => { console.log('Hi'); }, 1000);
}
}
However, this approach doesn't work because intervalId
becomes undefined each time the component is called. Thus, old intervals continue running while new ones are added.
I'm unsure how to stop a currently running interval. Can you assist me with this?