Alex Alex - 2 months ago 12
TypeScript Question

How to run an interval on component init only once with angular2?

I have an interval launched in my component:

export class FoobarComponent implements OnInit {

ngOnInit(): void {
this.startInterval();
}

startInterval() void {
setInterval(() => { console.log('Hi'); }, 1000);
}
}


Each time the component is called, a new interval is created in addition to the previous ones.

I tried to used an ID (as I used to do with plain JS before) with something like:

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);
}
}


But it's not working since
intervalId
became undefined each time the component is called. So the previous intervals keep running while a new one is created.

I don't know how to stop an interval already running.
Could you help me to do it?

Answer

You can make the intervalID static. That way all class instances will be able to access the same one.

export class FoobarComponent implements OnInit {

    static intervalId: Number;

    ngOnInit(): void {
        this.startInterval();
    }

    startInterval() void {
        if(FoobarComponent.intervalId) { // always undefined 
            window.clearInterval(this.intervalId);
        }
        FoobarComponent.intervalId = window.setInterval(() => { console.log('Hi'); }, 1000);
    }
}