Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
How to clear setInterval ID in Angular?

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 class="row mt-5">
  <div class="col-12">
    <div class="button-group d-flex justify-content-evenly">
      <button (click)="startTimer()" class="btn btn-primary">Start</button>
      <button (click)="stopTimer()" class="btn btn-danger">Stop</button>
    </div>
  <h1 class="mt-5" style="text-align: center">{{ timer }}</h1>
  </div>
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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);
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

    // clear the timer once you click the stop button set 0 the timer variable .
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);
    }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda