Reputation: 1163
setInterval() working fine for me and timer starts, but clearInterval() doesn't stop timer when counter value reached to 100. It running continuously. Any help appreciated.
Below is my component code -
export class AppComponent {
counter=0;
progressInterval;
ngOnInit(){
this.progressInterval=setInterval(()=>{
this.counter=this.counter+10;
if(this.counter>=100){
clearInterval(this.progressInterval);
}
},200);
}
}
Below is my component HTML code -
<p style="margin:20px;">
<ngb-progressbar
type="warning"
[value]="counter"
[striped]="true"
[animated]="true"
>{{counter}}</ngb-progressbar>
</p>
and here is screenshot which shows progressbar -
Thanks
Upvotes: 2
Views: 13146
Reputation: 621
There's a couple things to consider in any implementation of Interval in Angular:
Make sure you're only instantiating it once. In this example, if you were to leave the component and return before the counter was cleared, it would create a second instance while the original kept going.
Have a fail-safe clearing of the interval when leaving the page or component scope using OnDestroy. You always need to clear/dispose the interval when done.
import { Component, OnInit, OnDestroy } from '@angular/core';
[..]
export class YourComponent implements OnInit, OnDestroy {
progressInterval: any;
ngOnInit() {
[..]
}
ngOnDestroy() {
if (this.progressInterval) { clearInterval(this.progressInterval); }
}
}
Upvotes: 0
Reputation: 1066
It's due to this variable scope is limited for that current function only. and interval function have it's own this variable so it can't detect this.progressInterval variable.
Try using this way:
ngOnInit(){
const initScope = this;
this.progressInterval=setInterval(()=>{
initScope.counter=initScope.counter+10;
if(initScope.counter>=100){
clearInterval(initScope.progressInterval);
}
},200);
}
Upvotes: 0
Reputation: 1163
Issue got fix for me. I forgot to import "clearInterval" from "timers" module. Now i updated like below and it worked now.
import {
setInterval,
clearInterval
} from 'timers';
Thanks for all for helping me on this.
Thanks
Upvotes: 6
Reputation: 4090
Tested with ES6 modules (try this with chrome 61 onwards)
<script type="module">
class AppComponent {
constructor() {
this.counter = 0;
this.progressInterval;
}
ngOnInit() {
this.progressInterval = setInterval(() => {
this.counter += 10;
console.log('this.counter', this.counter);
if(this.counter >= 100){
clearInterval(this.progressInterval);
console.log('cleaned and finished');
}
},200);
}
}
const instance = new AppComponent();
instance.ngOnInit();
</script>
Your code with ES6 syntax works perfectly. Seems there is another behavior with Angular5 check this answer:
Angular 2 setinterval() keep running on other component
Upvotes: 0
Reputation: 501
Or you can assign the interval to a variable. Lets say like this:
ngOnInit() {
const int = setInterval( () => {
this.counter += 10;
if ( this.counter >= 100 ){
clearInterval( int );
}
}, 200);
}
Upvotes: 4