Estoy construyendo un temporizador básico en Angular. Para esto tengo dos botones, uno de ellos inicia el temporizador y el otro lo detiene. Estoy implementando setInterval con un retraso de 1000 ms. Pero cuando presiono el botón de detener, el temporizador se detiene pero el timeoutId no se borra. Quiero evitar que el usuario no inicie otro temporizador cuando el primero no finaliza. Yo uso - si (this.timeoutId) return; - Pero no soy capaz de volver a iniciarlo ya que lo detengo. La pregunta es cómo puedo evitar que el usuario inicie un nuevo temporizador cuando se inició el temporizador. Y cómo puedo empezar de nuevo cuando lo detengo.
//componente-control-del-juego.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); } }//componente-de-control-del-juego-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>No hay una forma incorporada para lograr esto.
La única solución posible es borrar la variable de intervalo una vez que borre el objeto de intervalo.
stopTimer() { clearInterval(this.timeoutId); this.timeoutId = null; // Clear the timeoutId }Y ahora el temporizador de inicio funciona como se esperaba. Está comprobando si el timeoutId existe dentro de la función del temporizador de inicio
startTimer() { if (this.timeoutId) return; // Function will exist from here if timeoutId exist this.timeoutId = setInterval(() => { this.increment(); this.onIncrement.emit(this.timer); }, 1000); } // 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); }