Estoy tratando de hacer un temporizador que comience al comienzo de la visualización de clasificación y se ejecute hasta que finalice la clasificación. El temporizador se inicia en consecuencia, pero no se detiene después de la clasificación. esto funciona absolutamente bien en Componente funcional (con gancho useEffect) pero no funciona en Componente de clase.
aquí está mi función startTimer -
startTimer = () => { let isAlgo = this.state.isAlgorithmSortOver; let interval; if (isAlgo === true) { interval = setInterval(() => { this.setState({ time: this.state.time + 10, }); }, 10); } else if (isAlgo === false) { clearInterval(interval); } // return () => clearInterval(interval); };y aquí está la función startVisualizer -
startVisualizer = () => { let steps = this.state.arraySteps; let colorSteps = this.state.colorSteps; this.clearTimeouts(); let timeouts = []; let i = 0; while (i < steps.length - this.state.currentStep) { let timeout = setTimeout(() => { let currentStep = this.state.currentStep; this.setState({ array: steps[currentStep], colorElement: colorSteps[currentStep], currentStep: currentStep + 1, isAlgorithmSortOver: false, }); //? comparing the currentStep with arraySteps and the state of isAlgorithmSortOver will remain false until the array is fully sorted.. Adding '+ 1' to currentStep because the arraySteps state always will be '+1' bigger than the currentStep.. if (currentStep + 1 === i) { this.setState({ isAlgorithmSortOver: true, }); } timeouts.push(timeout); }, this.state.delayAnimation * i); i++; } this.startTimer(); this.setState({ timeouts: timeouts, // isAlgorithmSortOver: false, }); };porque no estás limpiando el intervalo. Intente guardar la identificación del intervalo para indicar así:
startTimer = () => { let isAlgo = this.state.isAlgorithmSortOver; if (isAlgo === true) { interval = setInterval(() => { this.setState({ time: this.state.time + 10, }); }, 10); this.setState({interval}) } };Luego puede llamar a clearInterval donde quiera, así:
clearInterval(this.state.interval) También debe sacar timeouts.push(timeout) de setTimeout donde in while . Porque, de lo contrario, timeouts.push(timeout) no funciona sincrónicamente, funciona después de un tiempo.