Skip to main content

angular - How to use clearInterval()

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


export class AppComponent {
  counter:number = 0;
  isDisabled:boolean = false;
  timer:any;

  startCounting(){
    this.counter = 0;
    this.isDisabled = true;

    // Repeat executing a function at a specified time interval.
    this.timer = setInterval(() => this.updateCounter(), 1000)
   }

   stopCounting(){
    clearInterval(this.timer);
    this.isDisabled = false;
   }

   updateCounter(){
    this.counter++;
   }
}
app.component.html

<h2 style="padding-top:25px; padding-bottom:25px;">
    Angular - How to use clearInterval()
</h2>

<button 
    (click)="startCounting()" 
    [disabled]="isDisabled"
    style="margin-bottom:20px; padding:12px;">
        Start Counting (1 second interval)
</button>

&nbsp;

<button 
    (click)="stopCounting()" 
    [disabled]="!isDisabled"
    style="margin-bottom:20px; padding:12px;">
        Stop Counting
</button>

<h1>Counter : {{counter}}</h1>
More Angular tutorials