Home > Software design >  How to clear setInterval ID in Angular?
How to clear setInterval ID in Angular?

Time:02-11

I am building a basic timer in Angular. For this I have two button, one of them starts the timer and the other stops it. I am implementing setInterval with 1000ms delay. But when I press the stop button, the timer stops but the timeoutId is not cleared. I want to prevent the user not to start another timer when the first one doesnt finish. I use - if (this.timeoutId) return; - But I am not able to start it again as I stop it. The question is how I can prevent the user to start new timer when the timer started. And how can I start it again when I stop it.

//game-control-component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-game-control',
  templateUrl: './game-control.component.html',
  styleUrls: ['./game-control.component.css'],
})
export class GameControlComponent implements OnInit {

@Output() onIncrement: EventEmitter<number> = new EventEmitter();
timer: number = 0;
timeoutId!: ReturnType<typeof setTimeout>;

constructor() {
  console.log(this.timeoutId);
}

increment() {
  this.timer  ;
}

startTimer() {
  if (this.timeoutId) return;
  this.timeoutId = setInterval(() => {
    this.increment();
    this.onIncrement.emit(this.timer);
  }, 1000);
}

stopTimer() {
  clearInterval(this.timeoutId);
  console.log(this.timeoutId);
}

ngOnInit(): void {
  console.log(this.timeoutId);
 }

}

//game-control-component-html

<div >
  <div >
    <div >
      <button (click)="startTimer()" >Start</button>
      <button (click)="stopTimer()" >Stop</button>
    </div>
  <h1  style="text-align: center">{{ timer }}</h1>
  </div>

CodePudding user response:

There is no inbuilt way for achieving this.

The only possible solution is to clear the interval variable once you clear the interval object.

stopTimer() {
  clearInterval(this.timeoutId);
  this.timeoutId = null; // Clear the timeoutId
}

And now the start timer works as expexted. You are checking whether the timeoutId exist inside the start timer function

startTimer() {
  if (this.timeoutId) return; // Function will exist from here if timeoutId exist
  this.timeoutId = setInterval(() => {
    this.increment();
    this.onIncrement.emit(this.timer);
  }, 1000);
}

CodePudding user response:

stopTimer() {
  clearInterval(this.timeoutId);
  this.timer= 0; // Clear the timer
}
startTimer() {
  if (this.timeoutId) return; // remove this one
  this.timeoutId = setInterval(() => {
    this.increment();
    this.onIncrement.emit(this.timer);
  }, 1000);
}
  • Related